In this article I will discuss about some of the important inbuilt array methods in JavaScript. I will cover the following methods:
length, concat, sort, reverse, split, join, push, pop, unshift, shift, Array.isArray, forEach, map, filter
length:
The length()
methods returns the length of an array.
var fruits = ["Orange", "Apple", "Banana"];
console.log(fruits.length) // Output: 3
While dealing with arrays in programming, often we come across a situation where we need to check if the given array is empty or not. The length method can be used for the same. If the length of the array is zero, then it is empty.
var arr = [];
console.log(arr.length) // Output: 0
concat:
The concat() method is used to merge two or more arrays into single array. This method does not change the existing arrays, but instead returns a new array as you can see in the example below:
var arr1 = [1,2,3];
var arr2 = [4,5];
var arr3 = arr1.concat(arr2);
console.log(arr3); // Output: [1,2,3,4,5]
sort:
The sort()
method is used to sort an array elements in JavaScript. It returns sorted array.
var fruits = ["Orange", "Apple", "Banana"];
console.log(fruits.sort()); // Output: ["Apple","Banana","Orange"]
reverse:
The reverse()
method is used to sort an array elements in reverse order in JavaScript. It returns the array after the reversal.
var fruits = ["Orange", "Apple", "Banana"];
console.log(fruits.reverse()); // Output: ["Orange", "Banana", "Apple"]
split:
The split()
method splits the string into an array by the given delimiter or separator. For example, you can split a sentence into words array based on space as separator or any comma separated string into array of words.
var str1 = "JavaScript is awesome!"
console.log(str1.split(" ")); // Output: ["JavaScript", "is", "awesome!"]
var str2 = "Jan, Feb, Mar, Apr";
console.log(str2.split(", ")); // Output: ["Jan", "Feb", "Mar", "Apr"]
The split
method has an optional second numeric argument – a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used.
var str2 = "Jan, Feb, Mar, Apr";
console.log(str2.split(", ", 2)); // Output: ["Jan", "Feb"]
join:
The join() method does opposite of split i.e. it creates string out of array glued by given separator (as argument). If no separator or argument is provided, it returns comma separated string.
// Without separator
var months = ["Jan", "Feb", "Mar", "Apr"];
console.log(months.join()); // Output: Jan,Feb,Mar,Apr
// With separator
var months = ["Jan", "Feb", "Mar", "Apr"];
console.log(months.join("-")); // Output: Jan-Feb-Mar-Apr
push and pop:
The push()
method is used to add one or more elements at the end of an array. The element is provided as an argument. It returns array with the pushed element.
var months = ["Jan", "Feb", "Mar", "Apr"];
// add one element
months.push("May");
console.log(months); // Output: ["Jan", "Feb", "Mar", "Apr", "May"]
// add multiple elements
months.push("Jun","Jul");
console.log(months); // Output: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
The pop()
deletes last element from an array and returns rest of the array.
var months = ["Jan", "Feb", "Mar", "Apr"];
console.log(months.pop()); // Output: ["Jan", "Feb", "Mar"]
unshift and shift:
The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.
var months = ["Jan", "Feb", "Mar", "Apr"];
console.log(months.unshift("May", "Jun")); // Output: 6
console.log(months) // Output: ["May", "Jun", "Jan", "Feb", "Mar", "Apr"]
The shift()
method removes the first element from an array and returns that removed element. This method reduces the length of the array by one.
var months = ["Jan", "Feb", "Mar", "Apr"];
var firstElement = months.shift();
console.log(firstElement); // Output: Jan
console.log(months) // Output: ["Feb", "Mar", "Apr"]
Array.isArray:
In the previous article – Data Types in JavaScript, we have seen that data type of an Array
in JavaScript is Object
. The typeof
operator does not help is differentiating array from object as it returns Object
on both cases.
var obj = {foo: "bar"}; // Object
var arr = [1, 2, 3]; // Array
console.log(typeof obj); // Output: Object
console.log(typeof arr); // Output: Object
Then how do you check if a given value is array in JavaScript? The answer is: using Array.isArray()
method.
The Array.isArray()
method determines whether the passed value is an Array
or not. It accepts value as argument and returns true
if the value passed is an array, otherwise it returns false
.
Array.isArray([1, 2, 3]); // Output: true
Array.isArray({foo: "bar"}); // Output: false
Array.isArray('Hello'); // Output: false
Array.isArray(undefined); // Output: false
forEach:
The forEach()
method is used to loop through an array elements. The loop executes once for each array element.
var months = ["Jan", "Feb", "Mar", "Apr"];
months.forEach(function(element){
console.log(element);
})
// The loop will iterate four times
// Output:
"Jan"
"Feb"
"Mar"
"Apr"
Using JavaScript ES6 Arrow Function we can achieve the same with just single line of code.
var months = ["Jan", "Feb", "Mar", "Apr"];
months.forEach(element => console.log(element));
map:
The map()
method in JavaScript creates a new array with the results of calling a function for every array element. The provided function is called once for each array element. The map
method does not alter the original array. Note that map method works on all modern browsers except IE.
const arr1 = [1,2,3,4];
// pass a function to map
const arr2 = arr1.map(x => x * 2);
console.log(arr2); // output: Array [2, 4, 6, 8]
// No change in the original array
console.log(arr1); // output: Array [1,2,3,4]
As you can see, we have passed a multiplier function which multiplies each array elements by 2.
filter:
The filter()
method creates a new array with elements that fall under a given criteria from an existing array.
var numbers = [1, 3, 6, 8, 11, 14];
var odd = numbers.filter(function(number) {
return number % 2 > 0 ; // Return odd numbers only
});
console.log(odd);
// Output: [ 1, 3, 11 ]
In the above example, the filter callback function checks if the number is odd using the modulas operator (%)
. Modulus operator returns the division remainder. The remainder >0 means the number is odd.
You can try the above examples here.
You may also read:
What is Callback in JavaScript