Handling Arrays with jQuery

An array is a commonly used data structure in any programming language as it can hold a collection of elements, each identified by at least one array index or key. It is the preferred choice for holding multiple values/collections as it allows item sorting, item removal, item retrieval from an array using index, and other useful operations. The array needs to be used properly in code as it may introduce runtime errors (‘index out of the range,’ for example) while accessing any item. This post examines how to implement different array operations using jQuery. Let’s begin.

Check if Variable is an Array

While communicating with the external APIs or third party APIs to fetch data, it’s important to check the type of object, otherwise they can break your code. jQuery provides the $.isArray() method to check if the variable is an array or not. It returns true if the object is an array, otherwise it returns false. It takes a variable name as an argument and returns true/false as a result. Take a look at the following code for reference:

var foo = [];
var bar = ["Apple", "Mango", "Strawberry"];
var baz = "Test";
console.log('foo is an array: ' + $.isArray(foo)); // Returns true
console.log('bar is an array: ' + $.isArray(bar)); // Returns true
console.log('baz is an array: ' + $.isArray(baz)); // Returns false

As you can see, foo and bar are array elements and baz is a variable holding a string value. jQuery.isArray() will return true for foo and bar and false for baz.

Find Index of an Item in Array

To get the index of any item in an array, use the jQuery.inArray() method. The $.inArray() method is similar to JavaScript's native .indexOf() method. It returns the index when a match is found, and -1 when it doesn't find a match. Remember, the index starts from 0 so when the first element matches the searched value, the method returns 0.
It accepts 3 parameters: value to search, array variable name, and the optional fromIndex value which indicates the index of the array at which to begin the search. The default is 0, which will search the whole array.
Take a look at the following code.

var fruits = ["Apple", "Mango", "Strawberry", "Plum"];
console.log('Index of Apple is: ' + $.inArray("Apple", fruits)); //Returns 0
console.log('Index of Banana is: ' + $.inArray("Banana", fruits)); //Returns -1
console.log('Index of Mango is: ' + $.inArray("Mango", fruits, 2)); //Returns -1

In the last line though mango is in the array, it appears before index 2 so -1 is returned.

Sort an Array

Sorting an array requires calling the JavaScript sort() method on the array object. By default, the sort() method sorts the values as strings in alphabetical and ascending order. It works well for string values, but requires an extra parameter (comparative function) to be passed for numerical values to get the correct sort order. See the below code:

var empfName = ["John", "Adam", "Steve", "Peter"];
empfName.sort() // Will produce Adam, John, Peter, Steve

The default implementation sorts in ascending order, but if descending order is needed, then call reverse() method after the sort() method. Shown here:

var empfName = ["John", "Adam", "Steve", "Peter"];
empfName.sort() // Will produce Adam, John, Peter, Steve
empfName.reverse() // Will produce Steve, Peter, John, Adam

Since the sort() method sorts everything as strings, note that a value like "35" is considered bigger than "135", because "3" is larger than "1". Therefore, to sort a numerical array, you need to pass a compare function. That way when the sort() method compares two values it sends the values to the compare function, and sorts the values according to the returned (negative, zero, or positive) value.

var age = [40, 70, 9, 98];
age.sort(); //Incorrect sort values. 40,70,9,98
age.sort(function(a, b){return a-b}); //Correct sort values. 9,40,70,98

Remove an Item from the Array

To remove an item from an array use the JavaScript splice() method. The splice() method adds/removes items to/from an array and returns the removed item(s). This method needs the index of the item to be removed. Most of the time we don’t know the index, so first we need to determine the index using $.inArray(). See the code:

var empfName = ["John", "Adam", "Steve", "Peter"];
  var nameToRemove = "Adam";
  empfName.splice($.inArray(nameToRemove, empfName), 1);

The first argument is the index of the element to be removed and the second argument denotes the number of items to be removed. If set to 0, no elements will be removed. If you use empfName.splice(1,2), then it will remove 2 items from the array which are at index 1. In this case, the remaining items would be John and Peter.
You can also add new items to an array using the splice() method. Like,

empfName.splice(2,0,"Mark");

The above line adds “Mark” to the array at the second index. So now the array items would be,
["John", "Mark”, "Peter"];

Remove Duplicate Items from an Array

There is no in-built method available to remove duplicate items from an array. You may find people using or suggesting jQuery.uniqueSort() or jQuery.unique(), but these methods work only on the array of DOM elements, not strings or numbers. So you need to write your own implementation. The following jQuery code creates a function removeDuplicate which uses jQuery.each and jQuery.inArray() to remove duplicate items. See this code:



function removeDuplicate(arrItems) {
  var newArr = [];
  $.each(arrItems, function(i, e) {
    if ($.inArray(e, newArr) == -1) newArr.push(e);
  });
  return newArr;
}
var numbers = [1, 4, 16, 10, 4, 8, 16];
var newArr = removeDuplicate(numbers);

Once this code is executed, the newArr array will have only unique items.

Merge Two Arrays into a Single Array

If you need to merge the content of two arrays into a single array, use the jQuery.merge() method. This method forms an array that contains all the elements from the two arrays. The order of items in each array is preserved with items from the second array appended. By nature, this method merges the content of two arrays into the first array only. Like so:

var arr1 = [10, 19, 22, 36, 50, 74, 10, 22];
var arr2 = [100,200,300];
var arr3 = $.merge(arr1, arr2);
In this case, the content of arr1 and arr3 would be the same. If you wouldn’t like to alter the content of the first array, then use the following code.
var arr1 = [10, 19, 22, 36, 50, 74, 10, 22];
var arr2 = [100,200,300];
var arr3 = $.merge($.merge([], arr1), arr2);

The inner merge first creates an empty array and clones the content of arr1, then the outer merge copies the content to the newly created array. Note that this does not update the content of the original array.

Conclusion

This post briefly examines some of the common array operations using jQuery’s inbuilt methods. These methods can help to discover any array element, merge two arrays, sort the new array, remove items from the array and remove duplicate items from an array. These methods are easy to use and allow you to implement difficult array operations with ease.



Responsive Menu
Add more content here...