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.

1const arr = [5, 12, 8, 130, 44, 130];
2const found = arr.find((element) => element > 50);
3// 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

1const arr = [1, 2, 3, 4, 5];
2// return the index of value 3 which is 3
3const isLargeNumber = arr.findIndex((element) => element > 2);

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

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

1const arr = [3, 2, 5, 6];
2console.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

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

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;

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

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.

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

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

1const returnDoubles = [1, 2, 3, 4, 5, 6].flatMap((v) => {
2 if (v % 2 === 0) {
3 return [v];
4 } else {
5 return [];
6 }
7});
8// [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().