12+ JavaScript Array Methods : You need to know
In this article, we will learn about some basic array methods and their uses.
Top most useful 12+ JavaScript Array Methods
ForEach
Loops over every element in an array and execute a callback function.
const arr = [1, 2, 3];
arr.forEach(num => console.log(num));
// 1, 2, 3
Map
Loops over each element in an array and execute a callback function and create a new array with the return values of the callback function.
const arr = [1, 2, 3, 4, 5];
const arrMulti= arr.map(num => num * 2);
// [2, 4, 6, 8, 10]
Filter
Loops over each array element and returns element which fulfill the condition.
const arr = [1, 2, 3, 4, 5];
const result= arr.filter(num => num > 2);
// [3, 4, 5]
Find
Finds the first element in the array that match a condition.
const arr = [1, 2, 3, 4, 5];
const result= arr.find(num => num === 3);
// 3
FindIndex
Same as the find method, it returns the index of the first element that fulfills a specific condition.
If none are found, -1
is returned.
const arr = [1, 2, 3, 4, 5];
const result= arr.findIndex(num => num === 3);
// 2
Every
This method takes a callback that returns a boolean value. Every() will return true if the condition is valid for ALL the elements in the array.
const arr = [1, 2, 3, 4, 5];
const result= arr.every(num => num > 2);
// False
slice()
The slice() method Will return new array but only with the extracted parts
For example:
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.slice(2) // ['c'.'d','e']
arr.slice(2, 4) // ["c", "d"]
arr.slice(-2) // ["d", "e"]
arr.slice(1, -2) // ["b", "c"]
splice()
The splice() method works the same as slice but difference is it does actually change the original array and Extracted elemented will gone from origianl array.
Basically we use it to just delete one or more eleemnet frpm an array using splice
arr.splice(2);
arr // ["a", "b"]
Remove last element using splice() method:
arr.splice(-1)
arr//["a","b","c","d","e"]
Reverse()
The reverse method is used to reverse array element.
const arr2 = ['j', 'i', 'h', 'g', 'f'];
console.log(arr2.reverse());
console.log(arr2);
concat()
const letters = arr.concat(arr2);
console.log(letters);
console.log([...arr, ...arr2]);
join()
console.log(letters.join(' - '));
Conclusion:
Do let me know If you face any difficulties please feel free to comment below we love to help you.
If you have any feedback suggestions then please inform us by commenting.
Don’t forget to share this tutorial with your friends on Facebook and Twitter