Most common array methods are ,
1 . forEach: Executes a provided function once for each array element.
const array = [1, 2, 3];
array.forEach(element => console.log(element));
2 . map: Creates a new array with the results of calling a provided function on every element in the calling array.
const array = [1, 2, 3];
const newArray = array.map(element => element * 2);
console.log(newArray); // Output: [2, 4, 6]
3 . filter: Creates a new array with all elements that pass the test implemented by the provided function.
const array = [1, 2, 3, 4, 5];
const newArray = array.filter(element => element % 2 === 0);
console.log(newArray); // Output: [2, 4]
4 . reduce: Executes a reducer function on each element of the array, resulting in a single output value.
const array = [1, 2, 3, 4, 5];
const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
5 . find: Returns the value of the first element in the array that satisfies the provided testing function.
const array = [1, 2, 3, 4, 5];
const found = array.find(element => element > 3);
console.log(found); // Output: 4
6 . some: Tests whether at least one element in the array passes the test implemented by the provided function.
const array = [1, 2, 3, 4, 5];
const hasEven = array.some(element => element % 2 === 0);
console.log(hasEven); // Output: true
7 . every: Tests whether all elements in the array pass the test implemented by the provided function.
const array = [2, 4, 6, 8, 10];
const allEven = array.every(element => element % 2 === 0);
console.log(allEven); // Output: true
These methods provide powerful ways to manipulate arrays in JavaScript and are commonly used in front-end development.
Top comments (0)