15 Must-Know JavaScript Array Methods
Tags: javascript, node, programming, typescript
Published: 2020-06-05 21:55:55

---
title: 15 Must-Know JavaScript Array Methods
published: true
date: 2020-06-05 07:51:01 UTC
cover_image: https://livecodestream.dev/images/post/2020-06-05-15-Must-Know-JavaScript-Array-Methods/Hero.jpg
tags: ["Javascript", "NodeJS", "Programming", "Typescript"]
canonical_url: http://livecodestream.dev/post/2020-06-05-15-must-know-javascript-array-methods/
---

Arrays are wonderful and a very particular type in JavaScript. There are many useful built-in properties and methods that will help you resolve any task which involves arrays. Today we are going to discuss 15 array methods every developer should know.

- some()
- every()
- reduce()
- map()
- flat()
- filter()
- forEach()
- findIndex()
- find()
- sort()
- concat()
- fill()
- includes()
- reverse()
- flatMap()

Notice the list is not enumerated as I don't believe one method is more important than the other, each of them will resolve a different problem, and thus is important we are familiar with all.

---

## some()
The `some()` tests whether **at least one** element in the array passes the test implemented by the `callback` function. The `callback` function will receive 3 arguments, the item, the index, and the full array. Additionally, is possible to assign a value for `this` when executing the `callback` by using the argument `thisArg`.

Definition:
```text
arr.some(callback(element[, index[, array]])[, thisArg])
```

Examples:
```javascript
const a = [1, 2, 3, 5, 8].some(item => item > 5)
const b = [1, 2, 3, 4, 5].some(item => item > 5)

console.log(a)
console.log(b)


---------
Output
---------
> true
> false
```

---

## every()
The `every()` method is in a way similar to the `some()` method, but it tests whether **all** the elements in the array pass the test implemented by the `callback` function.

Definition:
```text
arr.every(callback(element[, index[, array]])[, thisArg])
```

Examples:
```javascript
const a = [10, 9, 8, 7, 6].every(item => item > 5)
const b = [7, 6, 5].every(item => item > 5)

console.log(a)
console.log(b)


---------
Output
---------
> true
> false
```

---

## reduce()
The `reduce()` method executes a `callback` function once for each assigned value present in the array, taking 4 arguments:

1. accumulator
2. currentValue
3. currentIndex
4. array

The first time the `callback` is called, `accumulator` and `currentValue` can be either the `initialValue` if provided, and the first value in the array if not.

Definition:
```text
arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
```

### How reduce() works
Let's see with an example how `reduce()` works:
```javascript
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue)
```

If we go step by step and put in a table all the parameters plus the resulting value of the `callback`, we would get the following:

| #     | accumulator  | currentValue  | currentIndex   | array           | return value |
|-------|--------------|---------------|----------------|-----------------|--------------|
| 1     | 0            | 1             | 0              | [0, 1, 2, 3, 4] | 1            |
| 2     | 1            | 2             | 1              | [0, 1, 2, 3, 4] | 3            |
| 3     | 3            | 3             | 2              | [0, 1, 2, 3, 4] | 6            |
| 4     | 6            | 4             | 3              | [0, 1, 2, 3, 4] | 10           |

And the final result would be `10`. In our particular case I did not provide an initial value, let's try that next

```javascript
const initialValue = 10
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue, initialValue)
```

With this new scenario our table would like:

| # | accumulator | currentValue | currentIndex | array           | return value |
|---|-------------|--------------|--------------|-----------------|--------------|
| 1 | 10          | 0            | 0            | [0, 1, 2, 3, 4] | 10           |
| 2 | 10          | 1            | 1            | [0, 1, 2, 3, 4] | 11           |
| 3 | 11          | 2            | 2            | [0, 1, 2, 3, 4] | 13           |
| 4 | 13          | 3            | 3            | [0, 1, 2, 3, 4] | 16           |
| 5 | 16          | 4            | 4            | [0, 1, 2, 3, 4] | 20           |

And the final resulting value is `20`.

The `reduce()` function is great and it has several uses like sum all the values of an array or in an object array, counting for particular items in the array, grouping objects, merging arrays contained in array of objects, removing duplicates, etc.

---

## map()
The `map()` method **creates a new array** populated with the results of the `callback` function for each element in the array. Similar to the other methods, the `callback` function will receive 3 arguments, `currentValue`, `index`, and `array`. As is with the case of reduce(), the `callback` is only invoked for indexes of the array which have assigned values (including `undefined`).

Definition:
```text
arr.map(callback( currentValue[, index[, array]])[, thisArg])
```

Always be careful when using `map()`, remember that on each call will create a new array, if you don't actually need the array and you are simply trying to iterate, use `forEach()` or `for-of` instead.

Examples:
```javascript
const numbers = [1, 2, 3, 4, 5]
const doubled = numbers.map(value => value * 2)

console.log(doubled)

---------
Output
---------
> (5) [2, 4, 6, 8, 10]
```

As we mentioned `map()` will create a new array, so the following is a consequence of that:
```javascript
const numbers = [1, 2, 3, 4, 5]
const numbers2 = numbers.map(value => value)
console.log('numbers', numbers)
console.log('numbers2', numbers2)
console.log(numbers === numbers2)

---------
Output
---------
numbers (5) [1, 2, 3, 4, 5]
numbers2 (5) [1, 2, 3, 4, 5]
false
```
Even though each array contains the exact same elements, they are not the same reference and thus the `numbers === numbers2` resolves to false.

---

## flat()
The `flat()` method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. By default, it will flatten 1 level.

Definition:
```text
arr.flat([depth])
```

Examples:
```javascript
const arr1 = [1, 2, [3, 4]]
console.log(arr1.flat())

const arr2 = [1, 2, [3, 4, [5, 6]]]
console.log(arr2.flat())

const arr3 = [1, 2, [3, 4, [5, 6]]]
console.log(arr3.flat(2))

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
console.log(arr4.flat(Infinity))

---------
Output
---------
> (4) [1, 2, 3, 4]
> (5) [1, 2, 3, 4, Array(2)]
> (6) [1, 2, 3, 4, 5, 6]
> (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

Note that if we want to flatten all levels recursively we can pass `Infinity` as the argument of the function.

---

## filter()
Together with `map()` I think it's one of my favorites. The `filter()` method **creates a new array** with all the elements that pass the test implemented by the `callback` function.

Definition:
```text
arr.filter(callback(element[, index, [array]])[, thisArg])
```

Examples:
```javascript
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i == 0) {
      return false
    }
  }
  return num > 1
}

console.log(array.filter(isPrime))

---------
Output
---------
> (6) [2, 3, 5, 7, 11, 13]
```

---

## forEach()
The `forEach()` method executes a provided function once for each array element.

Definition:
```text
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
```

Example:
```javascript
const array = [1, 2, 3, 4, 5]
array.forEach((item) => console.log(item))

---------
Output
---------
1
2
3
4
5
```

There are 2 important considerations when using `forEach()`
- There is no way to stop or break a `forEach()` loop other than throwing an exception.
- `forEach()` expects a synchronous `callback`, it won't wait for promises to be resolved.

Let's see an example of the latter:
```javascript
let ratings = [5, 4, 5]
let sum = 0

let sumFunction = async function (a, b)
{
  return a + b
}

ratings.forEach(async function(rating) {
  sum = await sumFunction(sum, rating)
})

console.log(sum)

---------
Output
---------
0
```

Even though we would have expected the variable `sum` to have accumulated all the values in the array and have a value of `14`, the output was `0` as the `forEach()` statement ended without awaiting for the promises, and thus the `console.log` statement was executed before the variable `sum` was updated. So be very aware of this situation as it can lead to your code producing unexpected results.

---

## findIndex()
The `findIndex()` method returns the **index** of the first element in the array that satisfies the provided `callback` function. Otherwise, it returns -1, indicating that no element passed the test. Unlike with other methods, `findIndex()` will execute the `callback` function even for indexes with unassigned values.

Definition:
```text
arr.findIndex(callback( element[, index[, array]] )[, thisArg])
```

Example:
```javascript
function isPrime(num) {
  for (let i = 2; num > i; i++) {
    if (num % i == 0) {
      return false
    }
  }
  return num > 1
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime))
console.log([4, 6, 7, 9, 12].findIndex(isPrime))

---------
Output
---------
-1
2
```

---

## find()
The `find()` method is similar to the `findIndex()` method, however, it returns the **value** of the **first** element which satisfies the provided `callback` function as supposed to its index. If no element satisfies the `callback` then `undefined` is returned. 

Definition:
```text
arr.find(callback(element[, index[, array]])[, thisArg])
```


Example:
```javascript
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
]

const result = inventory.find( ({ name }) => name === 'cherries' )

console.log(result)


---------
Output
---------
> {name: "cherries", quantity: 5}
```

---

## sort()
The `sort()` function is very common and simply allows us to sort the elements of an array **in place** and returning the sorting array. The default sort order is ascending. The complexity and performance of this method cannot be guaranteed as it depends on the implementation.

Definition:
```text
arr.sort([compareFunction])
```

Examples:
```javascript
const numbers = [4, 2, 5, 1, 3]
numbers.sort((a, b) => a - b)
console.log(numbers)

---------
Output
---------
> (5) [1, 2, 3, 4, 5]
```

Always remember that the sorting happens in place, so:

```javascript
const numbers = [4, 2, 5, 1, 3]
const numbers2 = numbers.sort((a, b) => a - b)

console.log('numbers', numbers)
console.log('numbers2', numbers2)
console.log(numbers === numbers2)

---------
Output
---------
numbers > (5) [1, 2, 3, 4, 5]
numbers2 > (5) [1, 2, 3, 4, 5]
true
```

The sort function will modify the existing array, and return a reference to the same array, and thus the original array and the returned array will be the same.

---

## concat()
The `concat()` method is used to merge two or more arrays into **a new array**.

Definition:
```text
const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]])
```

Examples:
```javascript
const letters = ['a', 'b', 'c']
const numbers = [1, 2, 3]

console.log(letters.concat(numbers))

---------
Output
---------
> (6) ["a", "b", "c", 1, 2, 3]
```

---

## fill()
The `fill()` method changes all the elements in an array to a static value, from a start index (default `0`) to an end index (default `array.length`). The updates will happen **in place** and will return a reference to the same array.

Definition:
```text
arr.fill(value[, start[, end]])
```

Examples:
```javascript
const original = [1, 2, 3]
const result = original.fill(4)
console.log('original', original)
console.log('result', result)
console.log(original === result)

---------
Output
---------
original > (3) [4, 4, 4]
result > (3) [4, 4, 4]
true
```

---

## includes()
The `includes()` method determines whether an array includes a certain value among its entries, returning `true` or `false`. Note that the method `includes()` is case-sensitive when comparing strings and characters.

Definition:
```text
arr.includes(valueToFind[, fromIndex])
```

Examples:
```javascript
console.log([1, 2, 3].includes(2))
console.log([1, 2, 3].includes(4))

---------
Output
---------
true
false
```

---

## reverse()
The `reverse()` method reverses an array **in place**. By reversing we mean that the function will transpose the elements of the array, the first element will become the last, and the last the first element. This operation will mutate the original array and return a reference to the same.

Definition:
```text
a.reverse()
```

Examples:
```javascript
console.log([1, 2, 3].reverse())

---------
Output
---------
> (3) [3, 2, 1]
```

---

## flatMap()
The `flatMap()` method applies a function to each element of the array and then flatten the result into an array. It combines `flat()` and `map()` in one function.

Definition:
```text
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])
```

Example:
```javascript
const array = [[1], [2], [3], [4], [5]]

const a = array.flatMap(arr => arr * 10)


// With .flat() and .map()
const b = array.flat().map(arr => arr * 10)

console.log('flatMap', a)
console.log('flat&map', b)

---------
Output
---------
flatMap (5) [10, 20, 30, 40, 50]
flat&map (5) [10, 20, 30, 40, 50]
```

---

## Summary

JavaScript arrays come with some great methods that can simplify our development efforts. Knowing them can save us some time and in some cases even boost the performance of our code. I hope that today you learned some new array methods, or refresh on old concepts which you can use for your next project.

Please let me know on the comments if you come up with great functions that can be simplified using the methods above, and don't forget to like the article if you enjoyed it, it helps me a lot when deciding which articles to write next.

Thanks for reading!