ES6: Array methods

Arrays are one of the fundamental data structures supported in most programming environments out-of-the box (you can even use an array in ASSEMBLY). Often times, a collection of built-in array methods are provided by the language itself. This is a compilation of those in modern JavaScript (ES6).

map()

Returns a new array based on an existing array where the function passed is executed for each element on the array.

let myArray = [1, 3, 5, 7, 9]
myArray.map(el => el + 1)
//=> [ 2, 4, 6, 8, 10 ]

filter()

Returns a new array based on truth condition on callback function passed to it.

let myArray = [1, 3, 5, 7, 9]
myArray.filter(el => el > 0)
//=> [ 1, 3, 5, 7, 9 ]
myArray.filter(el => el > 4)
//=> [ 5, 7, 9 ]
myArray.filter(el => el > 10)
//=> []

find()

Returns the first value from the array that returns true for the conditional defined and stops iteration.

let myArray = [1, 3, 5, 7, 9]
myArray.find(el => el === 5)
//=> 5

let peopleArray = [{id: 1}, {id: 4}, {id: 7}]
peopleArray.find(el => el.id === 4)
//=> {id: 4}

includes()

Checks the reference we're passing is equal to any of the elements inside by their memory reference

// --- USE1 - primitive data types
array = [1,2,3,4,5]
array.includes(1) // true
array.includes(3, 2) // true
array.includes(3, 3) // false

// --- USE2 - objects
let newArray = [{id: 1}, {id: 4}, {id: 7}]
newArray.includes({id: 2})
//=> false

reduce()

Returns 1 value by performing some operation on all elements of an array

Persists the outcome of iterating over our elements in each subsequent iteration

array = [1,2,3,4,5]
array.reduce((accumulator, currentElement) => accumulator + currentElement, 0)
//=> 15
let myArray = [1, 3, 5, 7, 9]
myArray.map(el => el + 1)
//=> [ 2, 4, 6, 8, 10 ]