Linda Ojo

Underrated JavaScript Array Methods – Part 2

Published: 2020-11-16

Last week, we looked at a few JavaScript Array Methods which you can read about in my last article: Underrated JavaScript Array Methods – Part 1. We are rounding up this week with a few more methods.

- flat()

This method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Syntax – array.flat(depth?)

Note: Arguments followed by a question mark are optional.

const array = [ [1, 2], [3, 4], [[5, 6]] ];

const flattenedOnce = array.flat();
const flattenedTwice = array.flat(2);

// expected output: Array [1, 2, 3, 4, [5, 6]]

// expected output: Array [1, 2, 3, 4, 5, 6]

- reduceRight()

The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. This method comes in pretty handy when you want to specify items in a left-to-right manner but execute them in a right-to-left manner.

You could use reduceRight() method to replace Array.reverse().reduce()

const numbers = [[0, 0], [1, 1], [2, 2]];

const modifiedNumbers = numbers.reduceRight( (a, b) => a.concat(b) );

// expected output: Array [2, 2, 1, 1, 0, 0]

- lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex if this argument is available. The lastIndexOf() method is case-sensitive.

Syntax – array.lastIndexOf(searchValue, fromIndex?)

const names = ['John', 'Bolanle', 'Dwight', 'Mary'];

console.log( names.lastIndexOf('Dwight') );
// expected output: 2

// -1 is returned if the searchValue is absent in the Array 
console.log( names.lastIndexOf('Tiger') );
// expected output: -1

See you next week 💙

Subscribe to Newsletter

Be the first to know about quality articles and poems written by Linda Ojo.