JS Bits - Array Methods

Welcome to JS Bits

Hello everyone, welcome to the first post on my new series JS Bits where I explain and also show you use cases where you can use them.

Array Methods

Array.prototype.find(callback)

Takes a callback function that returns the value of the first element that satisfies the condition.

const arr = [5, 12, 8, 130, 44, 130];
const found = arr.find(element => element > 50);
// found is equal to 130. It found the value 130 in the third index and returned it.

Array.prototype.findIndex(callback)

Similar to find method, returns the index of the first value that satisfies the condition

const arr = [1,2,3,4,5];

const isLargeNumber = arr.findIndex((element) => element > 3); // return the index of value 4 which is 3

Array.prototype.includes(valueToFind[, fromIndex])

Returns true or false whether the array includes the given value.

const arr = [3,2,5,6]
console.log(arr.includes(5)) // returns true

As an optional argument includes takes a parameter fromIndex which means where to begin the searching for the valueToFind

const arr = [3,2,5,6]
console.log(arr.includes(5, 2)) // starts searching the value 5 in arr beginning from the second index which returns true.

Array.prototype.flat([depth])

Creates a new flattend array with all the sub-array (nested parts) values taken out and concentinated in to the higher depth.

You will understand it better with this example;

// we have a nested array like this
const arr = [1,2,[3,4], 5, 6, [[7]] 
// this array has [3,4] which goes one level deeper and empty array of [[]] which goes two levels deeper
const newArr = arr.flat() // default value is one, returns the array: [1,2,3,4,5,6,[7]]
const otherARr = arr.flat(2) // goes to the depth of two and returns: [1,2,3,4,5,6,7]

Array.prototype.flatMap(callback(currentValue[, index[, array]])

It is very common now to use functional programming or FP methods in JavaScript like map().

If you want to use flat() on an array you are mapping. You have to first map(), which creates a new array and then call the flat() method.

flatMap() combines a map and a flat with a depth of one by first mapping each element and then running flat on the newly created array.

const arr = [1, 2, 3, 4];
const doubleArr = arr.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

A very good use case of flatMap() is adding or removing items during a map().

const returnDoubles = [1,2,3,4,5,6].flatMap((v) => {
    if(v % 2 === 0) {
        return [v];
    } else {
        return [];
    }
})
// [2,4,6]

Keep in mind that if you want to run flatMap() with a depth different than one(1). You have to call flat() additionally with a map().

Want to learn more about me? Here's my portfolio

No Comments Yet