An array is used to store the elements of multiple data types in JavaScript altogether. Also, there are certain times when you have to manipulate the response received from the APIs as per the requirements on the webpages. Sometimes, the responses are objects and have to be converted to the arrays to perform the desired operations. These methods of array manipulation can save your time.
-
map() Method: It iterates over every element of the array and applies some functional condition and return the new array. It does not change the main array but returns the new array of transformed values. Also, it uses the shorthand notation of the arrow function to decrease the code in a single line.
Javascript
var
abc = [10, 20, 30, 40, 50];
let xyz = abc.map(res => res * 2);
console.log(
"The main array: "
, abc);
console.log(
"The modified array: "
, xyz);
Output:
The main array: [10, 20, 30, 40, 50] The modified array: [20, 40, 60, 80, 100]
-
Filter() Method: This method is useful when you want to find out the elements which pass a certain condition. It iterates over all the elements and returns an array with the ones which satisfy the condition.
Also, it does not mutate the main array and creates the new one.Javascript
let abc =[10, 20, 30, 40, 50];
let xyz = abc.filter(res => res > 35);
console.log(
"The main array: "
, abc);
console.log(
"The modified array: "
, xyz);
Output:
The main array : [10, 20, 30, 40, 50] The modified array: [40, 50]
Note: The filter() method is widely compatible in IE because it belongs to ES5 and find() is introduced in ES6 so only the latest browsers (IE 11) are compatible with it.
-
Find() Method: This method can be used when you want to find out the element which passes a certain condition. This is very similar to the filter() method but it returns the first element which satisfies the condition and does not iterate further.
Javascript
let abc = [10, 20, 30, 40, 50];
let xyz = abc.find(res => res > 35);
console.log(
"The main array: "
, abc);
console.log(
"The modified array: "
, xyz);
Output:
The main array: [10, 20, 30, 40, 50] The modified array: [40]
-
Reduce() Method: This function is useful when you want to reduce all the elements of the array to a single value. It can be used to simply find out the addition of all the elements in an array.
Javascript
let abc =[10, 20, 30, 40, 50];
let xyz = abc.reduce((element, iterator)=>iterator+element, 0);
console.log(
"The addition is: "
, xyz);
Output:
The addition is: 150
Also, you can initialize the value of the element variable to some other value as well.
Javascript
let abc = [10, 20, 30, 40, 50];
let xyz = abc.reduce((element, iterator)
=> iterator + element, 2000);
console.log(
"The main array: "
, abc);
console.log(
"The addition is: "
, xyz);
Output:
The main array: [10, 20, 30, 40, 50] The addition is: [2150]