Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Monday, January 13, 2014

Sorted Array Push Using Lodash

Using the Array.push() method, you can push elements onto the end of a given array instance. That's handy for when you're first building an array, and assuming that you're not maintaining the sort order of the array. But what if you've already got an array, one that's populated with elements? In this case, Array.splice() is your friend — you use this to insert elements at the specified index position. If all you're doing is trying to add elements to an array while maintaining the sort order, you can use Lodash.

Tuesday, December 10, 2013

Chains and Flattened Arrays

The Lodash JavaScript utility library has plenty of array and collection functions, such as _.flatten(). Often, we end up having to apply several of these functions in succession in order to end up with the desired result. This becomes a much simpler programming task when using the _.chain() function to setup a chainable object first. The end result is a less awkward approach to successive function calls on the same object.

Monday, October 19, 2009

jQuery Array Deletion

The jQuery javascript toolkit provides several useful utility functions for working with arrays. One wouldn't think that this functionality would be necessary but in the world of javascript, this is often the case because of different browser implementations. The array utility functionality offered by jQuery includes basic array manipulation and searching.

One such searching function is the jQuery.inArray() function. As the name suggests, the function will determine if a specified element exists in a specified array. This utility is indispensable for javascript developers simply because of the amount of code it reduces.

Searching for elements in a javascript array often involves some kind of looping construct. In each iteration, we check if the current element is the desired element. In the case of array element deletion, we do something like this. The example below illustrates how the jQuery.inArray() function compliments the primitive splicing functionality of javascript arrays.
//Example; jQuery array deletion.

//Make the array.
var my_array=jQuery.makeArray(["A", "B", "C"])
console.log(my_array);

//Find an element to delete.
var my_pos=jQuery.inArray("B", my_array);
console.log(my_pos);

//Delete the element only if it exists.
my_pos < 0 || my_array.splice(my_pos, 1);
console.log(my_array);
In this example, we use the jQuery.makeArray() function because it returns a true array. It isn't needed but is a good practice regardless. Next, we find the position of the element we want to delete. Finally, if the my_pos value is less than 0, the element wasn't found and nothing happens. Otherwise, we splice the element out of the array. With the help of jQuery, we are able to seek and destroy array elements with two lines of code.