Additional Array Methods in JavaScript
Introduction
JavaScript arrays offer many advanced methods to manipulate elements, find values, and transform arrays efficiently. 🧩
1️⃣ findLast()
Returns the last element that satisfies a condition.
Code Snippet
const arr = [1, 2, 3, 4, 5];
console.log(arr.findLast(x => x % 2 === 0)); // 42️⃣ findLastIndex()
Returns the index of the last element that satisfies a condition.
Code Snippet
const arr = [1, 2, 3, 4, 5];
console.log(arr.findLastIndex(x => x % 2 === 0)); // 33️⃣ at()
Access elements using positive or negative index.
Code Snippet
const arr = [10, 20, 30];
console.log(arr.at(-1)); // 304️⃣ copyWithin()
Copies a portion of the array to another location in the same array.
Code Snippet
const arr = [1,2,3,4,5];
arr.copyWithin(0,3);
console.log(arr); // [4,5,3,4,5]5️⃣ fill()
Fills elements of an array with a static value.
Code Snippet
const arr = [1,2,3];
arr.fill(0);
console.log(arr); // [0,0,0]6️⃣ reverse()
Reverses the array in place.
Code Snippet
const arr = [1,2,3];
arr.reverse();
console.log(arr); // [3,2,1]7️⃣ flatMap()
Maps each element and flattens the result into a new array.
Code Snippet
const arr = [1,2,3];
const result = arr.flatMap(x => [x, x*2]);
console.log(result); // [1,2,2,4,3,6]8️⃣ every()
Checks if all elements satisfy a condition.
Code Snippet
const arr = [2,4,6];
console.log(arr.every(x => x % 2 === 0)); // true9️⃣ some()
Checks if at least one element satisfies a condition.
Code Snippet
const arr = [1,3,4];
console.log(arr.some(x => x % 2 === 0)); // true