New Array methods were introduced, and widely used now. I find these extremely useful and many modern JS libraries are heavily dependent on these, e.g., UnderscoreJS

We’ll look at common used Array methods

Map

The map() method creates a new array with the results of calling a function for every array element.

Parameters

Callback - produces an element of the new Array & runs over each element

currentValue - current element being processed

index - index of current Array element

array - array map was called upon

var numbers = [1,2,3,4];

var ary1=numbers.map (function (item,index) {

return item *2;

});

console.log(ary1); // [2, 4, 6, 8]

Therefore, the above code leverages Map method & iterates over each item and produces a new Array containing product by 2. Index is optional to pass & you could use inside callback function (item,index)

Reduce

The reduce() method reduces the array to a single value.

Parameters

A callback function runs on each value and takes four arguments:

previousValue - value returned previously

currentValue - current element being processed

index - index of current Array element

array - array map was called upon

Example

var numbers = [1,2,3,4];

var total=numbers.reduce (function (prev,current) {

return prev+current;

});

console.log(total); // 10

Look at stack trace where prev & current values could be debugged. This method processes two values at a time.

Filter

It creates a new array with all elements which pass the test.

Parameters

Callback - to test each element of array. It return true to keep the element, false otherwise.

var numbers = [1,2,3,4];

var ary1 = numbers.filter (function (value) {

return value > 2;

});

console.log (ary1); // [3,4]

Find

It returns a value in array if it’s found, otherwise undefined is returned.

Parameters

Callback - to test each element of array.

element - current processed value.

index - index of current Array element.

array - array map was called upon.

var numbers = [1,2,3,4];

var value = numbers.find (function (element) {

return element == 2;

});

console.log(value); // 2

Every

The purpose of this method is to iterate over each element of an Array and validate for all elements. Here is the syntax from VSCode.

Example

function isPrime(number)

{

var start = 2;

while (start <= Math.sqrt(number))

{

if (number % start++ < 1) returnfalse;

}

return number > 1;

}

var numbers = [3, 5, 7];

var flag = numbers.every(isPrime);

console.log(flag); // returns true

Summary

Please use these methods as it simplifies your code and reduces your time in these operations.