Mostly used Array methods
Map: it is used to transform the data and return new array without affecting the existing one.
let array = [1,2,3,4,5];
let newArray = array.map((val) => {
return val * 10;
});
console.log(‘Original Array = ‘, array); // [1, 2, 3, 4, 5]
console.log(‘Modified Array = ‘, newArray); // [10, 20, 30, 40, 50]
Filter: It can be used to create new array with elements passes the condition given by function or user.
let array = [1,2,3,4,5,6,7];
let newArray = array.filter((val) => {
return val % 2 === 0;
});
console.log(‘Original Array = ‘, array); // [1, 2, 3, 4, 5, 6, 7]
console.log(‘Modified Array = ‘, newArray); // [2, 4, 6]
Reduce: It is returning one value which is accumulated result of the function. It doesn’t affect the original array but create new one.
let array = [1,2,3,4,5];
let result = array.reduce((total, currentValue) => {
return total + currentValue;
});
console.log(‘Result = ‘, result); // Result = 15
indexOf: This method returns the first index of specified value else returns -1.
In order to check particular element exist in an array or not we can use indexOf, includes methods as well.
let array = [1,2,3,4,5];
let index = array.indexOf(4);
console.log(‘Index = ‘, index); // Index = 3
Push: It is used to push new element in an array.
let array = [1,2,3,4];
array.push(5);
console.log(‘Array = ‘, array); // Array = [1, 2, 3, 4, 5]
Pop: It is used to remove the last index value from array.
let array = [1,2,3,4];
array.pop();
console.log(‘Array = ‘, array); // Array = [1, 2, 3]
forEach: This function calls method for each element of an array. It doesn’t return any value or return undefined.
let array = [1,2,3,4,5];
let sum = 0;
array.forEach((val) => {
sum = sum + val;
});
console.log(‘Sum = ‘, sum);
Reverse: This method is used to reverses the array and overwrites the original array.
let array = [1,2,3,4,5];
array.reverse();
console.log(‘Reversed Array = ‘, array); // Reversed Array = [5, 4, 3, 2, 1]
to be continued…