DEV Community

Cover image for Understand JavaScript Array Methods with Code Experiments
Yuko
Yuko

Posted on • Updated on

Understand JavaScript Array Methods with Code Experiments

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, 2) return new array, 3) return a piece of array, 4) return a boolean value, 5) convert to string, 6) transform to value, and 7) loop array without returning a new array.

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

    let arr = [1, 2, 3, 4, 5]
    arr.push(6)
    console.log(arr) // [ 1, 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

add at start: .unshift

    arr.unshift(0)
    console.log(arr) // [ 0, 1, 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

remove at end (and return the deleted value) : .pop

    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
Enter fullscreen mode Exit fullscreen mode

remove at start (and return the deleted value): .shift

    console.log(arr) // [ 0, 1, 2, 3, 4, 5]
    deleted = arr.shift()
    console.log(arr) // [ 1, 2, 3, 4, 5 ]
    console.log(deleted) // 0
Enter fullscreen mode Exit fullscreen mode

cheat sheet for .push, .pop, .unshift, .shift

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)

    // 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 ]
Enter fullscreen mode Exit fullscreen mode

If you just want a part of array, consider using .slice instead.
Array.prototype.splice() - JavaScript | MDN

reverse array: .reverse

    console.log(arr) // [ 100, 101, 102, 103, 104 ]
    arr.reverse()
    console.log(arr) //[ 104, 103, 102, 101, 100 ]
Enter fullscreen mode Exit fullscreen mode

sort array: .sort

The default is ascending and convert to string, then comparing their sequences of UTF-16 code units values.

    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)
Enter fullscreen mode Exit fullscreen mode

Array.prototype.sort() - JavaScript | MDN

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)

    // 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 ]
Enter fullscreen mode Exit fullscreen mode

Group 2 Return new array

loop array and compute from the original array: .map

    // 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 ] 
Enter fullscreen mode Exit fullscreen mode

filter by using condition: .filter

    console.log(arr) // [ 0, 1, 2, 2, 1, 1 ]
    let newArr = arr.filter(element=>element === 1)
    console.log(newArr) // [ 1, 1, 1 ]
Enter fullscreen mode Exit fullscreen mode

portion of original: .slice

    // 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 ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.slice() - JavaScript | MDN

adding original to other: .concat

    // 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 ]
Enter fullscreen mode Exit fullscreen mode

flattening the original

simply flattering array: .flat

    // 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 
Enter fullscreen mode Exit fullscreen mode

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() followed by a flat() of depth 1, but slightly more efficient than calling those two methods separately.

    // 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' ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.flatMap() - JavaScript | MDN

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.

    // 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
Enter fullscreen mode Exit fullscreen mode

based on test condition: .findIndex

This method returns the first match element of the index based on a test condition.

    // example
    let arr = [1,2,3,2,1]
    const isEven = (element)=>element%2 === 0
    const indexIsEven = arr.findIndex(isEven)
    console.log(indexIsEven) // 1
Enter fullscreen mode Exit fullscreen mode

return an element: .find

This method returns the first match element based on a test condition.

    // example
    let arr = [1,2,3,4,5,6]
    const isEven = (element)=>element%2 === 0
    const elementIsEven = arr.find(isEven)
    console.log(elementIsEven) // 2
Enter fullscreen mode Exit fullscreen mode

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.

    // examples
    const isOne = arr.includes(1)
    console.log(isOne) // true

    const isSeven = arr.includes(7)
    console.log(isSeven) // false
Enter fullscreen mode Exit fullscreen mode

based on test condition

to know at least one element meets the condition: .some

    // 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
Enter fullscreen mode Exit fullscreen mode

to know all elements meet the condition: .every

    // 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
Enter fullscreen mode Exit fullscreen mode

Group 5 convert to string

.join

    // 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'
Enter fullscreen mode Exit fullscreen mode

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.

    // 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 ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.reduce() - JavaScript | MDN

Group 7 loop array without return new array

.forEach

This method executes a provided function once for each array element.

    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)
    }
Enter fullscreen mode Exit fullscreen mode

forEach does not wait for promises.

    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
Enter fullscreen mode Exit fullscreen mode

forEach() does not make a copy of the array before iterating.

    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 ]
Enter fullscreen mode Exit fullscreen mode

Array.prototype.forEach() - JavaScript | MDN

Thank you for reading :)
Array - JavaScript | MDN

The original article is here

Top comments (0)