Explain the Array functions in JavaScript

A JavaScript array can:

  • Hold values of different types.
  • The length of an array is dynamically sized and auto-growing.

Most of the array functions are used to transform or manipulate an array in some way.

In this post we will cover the following array functions:

  • map()
  • forEach()
  • reduce()
  • reduceRight()

map():

Takes an array, transforms its elements, and includes the results in a new array.

* * *

const array1 = [1, 4, 9, 16];

/ /  pass a function to map

const map1 = array1.map(x =>x * 2);

console. log( map1);

// output: Array [2, 8, 18, 32]

forEach():

Executes a function on every element of an array.

* * * 

let ranks = [‘A’ B ‘C’];

ranks.forEach( function (e) {

console. log(e);

});

/ / output: “A”

/ / output: “B”

/ / output: “C”

reduce():

Reduces an array into a value.

* * *

/ / calculate the total of elements of the array

let numbers = [1, 2, 3];

let sum = numbers.reduce( function (accumulator, current) {

return accumulator + current;

});

console. log( sum); / / 6

reduce():

The reducer function takes five arguments:

1.Accumulator: accumulates callback’s return

values.

2. Current Value: the current element being

processed.

3.Current Index (optional): the index of the current element being processed.

4. Source Array (optional): the array reduce) was called upon.

5. Initial Value (optional): the first argument to the first call of the callback. If no value is supplied,  the first element in the array will be used.

reduceRight():

Works in the same way as the reduce() method, but in the opposite direction.

* * * 

/ / calculate the total of elements of the array

let numbers = [1, 2, 3];

let sum= numbers.reduceRight( function (accumulator, current)

{

return accumulator + current;

});

console. log( sum) ; //6

Leave a Reply

Your email address will not be published. Required fields are marked *