If you want to work on array in javascript you must be aware of array operating functions which we have listed here for you. These are some of those methods which are frequently used when you work with arrays in javascript.
1- concat(): This method joins two or more arrays and return a new array containing all elements.
array1.concat(array2, array3, ..., arrayX)
var arr1 = ["abc", "def"];
var arr2 = ["ghi", "jkl", "mno"];
var res = arr1.concat(arr2);
2- includes(): This method searches in array to check whether the passing element is exist or not. It returns true if exist else return false and also it is case sensitive.
var arr2 = ["ghi", "jkl", "mno"];
var res = arr1.includes('jkl');
3- indexOf(): This method searches the sepcified element in the array and return its position if finds else return -1.
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
var res = animals.indexOf("Cat");
4- isArray(): This method checks whether the object is array or not. Returns true if it is array else returns false.
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
var res = Array.isArray(animals);
5- join(): This method joins array elements with specified separator. Default is comma ','
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
var res = animals.join();
6- keys(): Returns an array iterator object containing all keys of the array.
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
var res = animals.keys();
7- map(): This method calls a specified function for each value in the array and returns a new array.
array.map(function(currentValue, index, arr), thisValue)
var nums = [4, 9, 16, 25];
var res = nums.map(Math.sqrt)
8- push(): This method adds a new element at the end of the array and returns a new length.
array.push(item1, item2, ..., itemX)
var nums = [4, 9, 16, 25];
nums.push(36);
9- slice(): This method returns selected elements as a new array.
array.slice(start, end)
var nums = [4, 9, 16, 25, 30];
var res = nums.slice(1, 3);
10- sort(): This method sorts an array.
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
animals.sort();
11- splice(): This methods adds/removes elements from an array and returns removed items.
array.splice(index, howmany, item1, ....., itemX)
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
animals.splice(2, 0, "Lion", "Rabit");
12- toString(): Returns a string from array elemets separated by comma ','.
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
var res = animals.toString();
13- filter(): This method returns an array of elements which pass a test.
var nums = [4, 9, 16, 25, 30];
function checkNum(n) {
return n >= 16;
}
var res = nums.filter(checkNum);
14- forEach(): Calls a function once for each element in the array.
var animals = ["Dog", "Cat", "Tiger", "Elephant"];
animals.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "
";
}
15- from(): Creates an from string.
var res = Array.from("HelloWorld");