JavaScript

Table of contents

1. Array Manipulation

1.1 Iteration with map() and forEach()

The forEach() of an array instance is used to execute a function also known as a “callback function”, for all elements of an array. This callback function is passed the current item:

const list = [1, 2, 3]

list.forEach(element => {
  console.log(element * 2)
})

It’s similar to map(), however nothing is returned from forEach() while using map() we get a new array with the result of the function executed in the callback.

We can also get the index of the element as the second parameter to the callback function:

const list = [1, 2, 3]

list.forEach((element, index) => {
  console.log(element, index)
})

1.2 Filtering

Create a new array by filtering on elements from an existing one.
How do you choose? In the callback function that filter() accepts, we return true to include that item in the new array.

Example – Filter on even numbers:

const a = [1, 2, 3, 4, 5]

const even = a.filter((item) => {
  if (item % 2 === 0) return true
  return false
})

or 

// take an item and return true if the item % 2 is 0
const even = a.filter(item => item % 2 === 0)

>>> even
>>> [2, 4]

Example – Find a specific element in the array:

const a = [1, 2, 3, 4, 5]

// take an item and return true if the item is 4
// filter() returns an array
// shift() returns the first item in the array
const b = a.filter(item => item === 4).shift()

>>> b
>>> 4

Example – Remove an item from an array:

const a = [1, 2, 3, 4, 5]

// take an item and return true if the item is not 2
const b = a.filter(item => item !== 2)

>>> b
>>> [1, 3, 4, 5]

Example – Remove multiple items using includes():

const items = ['a', 'b', 'c', 'd', 'e', 'f']

const valuesToRemove = ['c', 'd']

const b = items.filter(item => !valuesToRemove.includes(item))

>>> b
>>> ["a", "b", "e", "f"]

1.3 Sorting

To sort an array alphabetically, we just use sort():

const a = ['b', 'd', 'c', 'a']
a.sort()

>>> a
>>> ['a', 'b', 'c', 'd']

Note: This does not work for numbers, as it sorts ASCII value (0-9A-Za-z).

To sort by number values we need to use custom functions:

const a = [1, 4, 3, 2, 5]

a.sort((a, b) => (a > b ? 1 : -1)) 

>>> a
>>> [1, 2, 3, 4, 5]

We can reverse the sort order of an array with reverse():

const a = [1, 2, 3, 4, 5]

>>> a.reverse()
>>> [5, 4, 3, 2, 1]

1.4 Searching

we can search arrays with find() and findIndex().

find() is used to find an item in the array:

We pass a function to if, and we get back the first item that returns true from it and returns undefined if not found.

a.find((element, index, array) => {
  //return true or false
})

const itemFound = items.find((item) => item.name === 'b')

findIndex() is similar but instead of the item, it returns the index of
the first item that returns true, and if not found, it returns undefined:

a.findIndex((element, index, array) => {
  //return true or false
})