ES6 Array methods

ES6 Array methods

First of all lets create a random array

let myNumber = 34943;
myArray = myNumber.toString().split('');

Foreach

Normal iteration, looping the array getting each element and index of the array. NB there’s the use of the JS arrow operator

myArray.forEach((item, index) => {
    console.log(item, index)
});

Map

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

let newArray = myArray.map((x) => parseInt(x));
console.log(newArray)

Filter

Filter does what the name suggests, it creates a new array by filtering elements that are false given a condition.

const evens = newArray.filter(item => item % 2 === 0);
console.log(evens);

Reduce

The reduce() method reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.

The callback argument is a function that will be called once for every item in the array. This function takes four arguments, but often only the first two are used.

  • accumulator – the returned value of the previous iteration
  • currentValue – the current item in the array
  • index – the index of the current item
  • array – the original array on which reduce was called
  • The initialValue argument is optional. If provided, it will be used as the initial accumulator value in the first call to the callback function.
let sum = newArray.reduce((res,item) => res + item,0)
console.log(sum)

Leave a Reply

Close Menu