Understand JavaScript Array Methods with Code Experiments
Tags: javascript, beginners, programming
Published: 2022-03-01 18:55:20


This is my memo about JavaScript Array Methods so that I can choose the appropriate methods depending on each situation.

I would like to explain based on the chart below. I divided these methods into seven groups: [1) mutate original array](#group-1-mutate-original-array), [2) return new array](#group-2-return-new-array), [3) return a piece of array](#group-3-return-a-piece-of-array), [4) return a boolean value](#group-4-return-a-boolean-value), [5) convert to string](#group-5-convert-to-string), [6) transform to value](#group-6-transform-to-value), and [7) loop array without returning a new array](#group-7-loop-array-without-return-new-array).

![](https://cdn-images-1.medium.com/max/7016/1*QY3UH96u-00gGV8KtlnA4Q.png)

Side note: I chose red for the group 1 because mutating the original array sometimes brings about miserable bugs during development processes. Similarly, I chose yellow for .forEach method because there are some pitfalls which we need to be aware of.

## Group 1 Mutate original array

Methods name: .push, .unshift, .pop, .shift, .splice, .reverse, .sort, .fill

### Add and Remove

**add at end: .push**
```javascript
    let arr = [1, 2, 3, 4, 5]
    arr.push(6)
    console.log(arr) // [ 1, 2, 3, 4, 5, 6 ]
```
**add at start: .unshift**
```javascript
    arr.unshift(0)
    console.log(arr) // [ 0, 1, 2, 3, 4, 5, 6 ]
```
**remove at end (and return the deleted value) : .pop**
```javascript
    console.log(arr) // [ 0, 1, 2, 3, 4, 5, 6 ]
    let deleted = arr.pop()
    console.log(arr) // [ 0, 1, 2, 3, 4, 5 ]
    console.log(deleted) // 6
```
**remove at start (and return the deleted value): .shift**
```javascript
    console.log(arr) // [ 0, 1, 2, 3, 4, 5]
    deleted = arr.shift()
    console.log(arr) // [ 1, 2, 3, 4, 5 ]
    console.log(deleted) // 0
```
![cheat sheet for .push, .pop, .unshift, .shift](https://cdn-images-1.medium.com/max/4612/1*lJjxnPPpzAmEUORpemdEsA.png)

### **Other mutable operations**

**change contents: .splice:**
>  This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place (and return an array containing removed elements)
```javascript
    // syntax 
    /*
     * @param {integer} start - The index at which to start changing the array.
     * @param {integer} [deleteCount] - An integer indicating the number of elements in the array to remove from start.
     * @param {...elements} [item] - The elements to add to the array, beginning from start.
    **/
    // !! data type is not actual JavaScript data type !!

    splice(start) 
    splice(start, deleteCount)
    splice(start, deleteCount, item1)
    splice(start, deleteCount, item1, item2, itemN)

    // examples
    console.log(arr) // [ 0, 1, 2, 3, 4, 5, 6 ]
    deleted = arr.splice(5)
    console.log(arr) //  [ 0, 1, 2, 3, 4 ]
    console.log(deleted) // [5,6]

    deleted = arr.splice(0,2)
    console.log(arr) // [ 2, 3, 4 ]
    console.log(deleted) // [ 0, 1 ]

    deleted = arr.splice(0,1,100)
    console.log(arr) // [ 100, 3, 4 ]
    console.log(deleted) // [ 2 ]

    deleted = arr.splice(1, 2, 101, 102, 103, 104)
    console.log(arr) // [ 100, 101, 102, 103, 104 ]
    console.log(deleted) // [ 3, 4 ]
```
If you just want a part of array, consider using .slice instead.
[**Array.prototype.splice() - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)

**reverse array: .reverse**
```javascript
    console.log(arr) // [ 100, 101, 102, 103, 104 ]
    arr.reverse()
    console.log(arr) //[ 104, 103, 102, 101, 100 ]
```
**sort array: .sort**
>  The default is ascending and convert to string, then comparing their sequences of UTF-16 code units values.
```javascript
    let arr = [1, 2, 10, 20, 100, 200]

    // default 
    arr.sort()
    console.log(arr) //[ 1, 10, 100, 2, 20, 200 ]

    // ascending order
    arr.sort((a, b)=> a-b)
    console.log(arr) // [ 1, 2, 10, 20, 100, 200 ]

    // descending order
    arr.sort((a,b)=>b-a)
    console.l0g(arr)
```
[**Array.prototype.sort() - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

**fill with a certain value: .fill**
>  This method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length)
```javascript
    // syntax
    /*
     * @param {element} start - Value to fill the array with.
     * @param {integer} [start] - Start index (inclusive), default 0.
     * @param {integer} [end] - End index (exclusive), default arr.length.
    **/
    // !! data type is not actual JavaScript data type !!

    fill(value)
    fill(value, start)
    fill(value, start, end)

    console.log(arr) // [ 200, 100, 20, 10, 2, 1 ]
    arr.fill(0)
    console.log(arr) // [ 0, 0, 0, 0, 0, 0 ]

    arr.fill(1, 1)
    console.log(arr) // [ 0, 1, 1, 1, 1, 1 ]

    arr.fill(2,2,4)
    console.log(arr) // [ 0, 1, 2, 2, 1, 1 ]
```
## Group 2 Return new array

### loop array and compute from the original array: .map
```javascript
    // an example
    console.log(arr) // [ 100, 101, 102, 103, 104 ]
    const newArr = arr.map(element=>element + 1)
    console.log(newArr) // [ 101, 102, 103, 104, 105 ]
    console.log(arr) // [ 100, 101, 102, 103, 104 ] 
```
### filter by using condition: .filter
```javascript
    console.log(arr) // [ 0, 1, 2, 2, 1, 1 ]
    let newArr = arr.filter(element=>element === 1)
    console.log(newArr) // [ 1, 1, 1 ]
```
### portion of original: .slice
```javascript
    // syntax
    /*
     * @param {integer} [start] - Zero-based index at which to start extraction.
     * @param {integer} [end] - Zero-based index *before* which to end extraction.
    **/
    // !! data type is not actual JavaScript data type !!

    slice()
    slice(start)
    slice(start, end)

    // examples
    let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    newArr = arr.slice()
    console.log(newArr) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

    console.log(arr) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    newArr = arr.slice(2)
    console.log(newArr) // [ 3, 4, 5, 6, 7, 8, 9, 10 ]

    console.log(arr) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    newArr = arr.slice(3, 6)
    console.log(newArr) // [ 4, 5, 6 ]
```
[**Array.prototype.slice() - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
### adding original to other: .concat
```javascript
    // an example 
    console.log(arr) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
    console.log(newArr) // [ 4, 5, 6 ]
    let concat = arr.concat(newArr)
    console.log(concat) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 6 ]
```
### flattening the original

**simply flattering array: .flat**
```javascript
    // syntax
    /*
     * @param {integer} [start] - The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
    **/

    flat()
    flat(depth)

    // examples
    arr = [1,[2,3],[[4,5]]]
    newArr = arr.flat()
    console.log(newArr) // [ 1, 2, 3, [ 4, 5 ] ]

    newArr = arr.flat(2)
    console.log(newArr) // [ 1, 2, 3, 4, 5 ]

    arr = [1, [2,3], [[4,5]], [[[6,7]]]]
    newArr = arr.flat(Infinity) // [ 1, 2, 3, 4, 5, 6, 7 
```
**with looping thorough each elements and flatten the array to be the depth 1: .flatMap**
>  This method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a [map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) followed by a [flat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) of depth 1, but slightly more efficient than calling those two methods separately.
```javascript
    // examples

    let arr = [1,2,3,4,5]
    let arr2 = ["a", "b", "c", "d", "e"]

    const flatMapArr = arr.flatMap(x=>[x ** 2])
    console.log(flatMapArr) //[ 1, 4, 9, 16, 25 ]

    // the difference b/w .map
    const mapArr = arr.map(x => [x ** 2]);
    console.log(mapArr) // [ [ 1 ], [ 4 ], [ 9 ], [ 16 ], [ 25 ] ]

    const flatMapArr2 = arr.flatMap((x, index) => [x, arr2[index]]);
    console.log(flatMapArr2) // [ 1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e' ]
```
[**Array.prototype.flatMap() - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap)

## Group 3 Return a piece of array

### return an array index

**based on value: .indexOf**

This method returns the first match element of the index based on an array index.
```javascript
    // examples

    let arr = [1,2,3,4,5]
    let indexOfValue1 = arr.indexOf(1)
    console.log(indexOfValue1) // 0

    arr = [1,2,3,2,1]
    indexOfValue1 = arr.indexOf(1)
    console.log(indexOfValue1) // 0

    const indexOfValue6 = arr.indexOf(6)
    console.log(indexOfValue6) // -1 return -1 if it doesn't exist
```
**based on test condition: .findIndex**

This method returns the first match element of the index based on a test condition.
```javascript
    // example
    let arr = [1,2,3,2,1]
    const isEven = (element)=>element%2 === 0
    const indexIsEven = arr.findIndex(isEven)
    console.log(indexIsEven) // 1
```
### return an element: .find

This method returns the first match element based on a test condition.
```javascript
    // example
    let arr = [1,2,3,4,5,6]
    const isEven = (element)=>element%2 === 0
    const elementIsEven = arr.find(isEven)
    console.log(elementIsEven) // 2
```
## Group 4 return a boolean value

### based on value: .includes

This method returns true if the array includes the given value and returns false if not.
```javascript
    // examples
    const isOne = arr.includes(1)
    console.log(isOne) // true

    const isSeven = arr.includes(7)
    console.log(isSeven) // false
```
### based on test condition

**to know at least one element meets the condition: .some**
```javascript
    // examples
    let arr = [1,2,3,4,5,6]
    let isArrayHasEven = arr.some(isEven)
    console.log(isArrayHasEven) // true

    arr = [1,3,5,7,9]
    isArrayHasEven = arr.some(isEven)
    console.log(isArrayHasEven) // false
```
**to know all elements meet the condition: .every**
```javascript
    // examples
    let allElementsAreEven = arr.every(isEven)
    console.log("1",allElementsAreEven) // false

    arr = [2, 4, 6, 8, 10, 12]
    allElementsAreEven = arr.every(isEven)
    console.log(allElementsAreEven) // true
```
## Group 5 convert to string

**.join**
```javascript
    // examples
    let arr = [2, 4, 6, 8, 10, 12]
    let joinedArray = arr.join('')
    console.log(joinedArray) // '24681012'

    joinedArray = arr.join('😋')
    console.log(joinedArray) // '2😋4😋6😋8😋10😋12'
```
## Group 6) transform to value

**.reduce**
>  The **reduce()** method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
```javascript
    // examples
    let arr = [1,2,3,4,5]
    let sum = arr.reduce((prev, curr)=>prev + curr)
    console.log(sum) // 15

    // set initvalue: 6
    sum = arr.reduce((prev, curr)=>prev + curr, 6)
    console.log(sum) // 21

    arr = [1,1,2,3,3,4,4,5]
    let noDupulications = arr.reduce((prev, curr)=>{
      if(prev.indexOf(curr)===-1){
        prev.push(curr)
      }
      return prev
    },[])
    console.log(noDupulications) // [ 1, 2, 3, 4, 5 ]
```
[**Array.prototype.reduce() - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)

## Group 7 loop array without return new array

**.forEach**
>  This method executes a provided function once for each array element.
```javascript
    let arr = [1,2,3,4,5]
    arr.forEach(element=> console.log(element))
    // 1
    // 2
    // 3
    // 4
    // 5

    // equivalent operation with for of
    for (let element of arr){
      console.log(element)
    }
```
>  forEach does not wait for promises.
```javascript
    let arr = [1,2,3,4,5]
    let multiply = 1

    const multiplyAsync = async (a, b) => a*b
    const multiplySync = (a, b) => a*b

    // async? 
    arr.forEach(async(element)=>{
      multiply = await multiplyAsync(multiply, element)
    })

    console.log("after async?",multiply) //1

    // sync
    multiply = 1
    arr.forEach(element=>{
      multiply = multiplySync(multiply, element)
    })
    console.log("sync",multiply) // 120
```
>  forEach() does not make a copy of the array before iterating.
```javascript
    let arr = [1,2,3,4,5]

    arr.forEach(element=>{
      console.log(element)
      if(element === 3){
        arr.shift()
      }
    })
    // 1
    // 2
    // 3
    // 5 <- got one earlier index (3) because 1 was removed

    console.log(arr) // [ 2, 3, 4, 5 ]
```
[**Array.prototype.forEach() - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)

Thank you for reading :)
[**Array - JavaScript | MDN**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)

The original article is [here](https://towardsdev.com/understand-javascript-array-methods-with-code-experiments-and-practical-examples-cb10c1543d13)