Underrated JavaScript Array Methods – Part 2

lindaojo

Linda

Posted on November 16, 2020

Underrated JavaScript Array Methods – Part 2

Alt Text

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);

console.log(flattenedOnce);
// expected output: Array [1, 2, 3, 4, [5, 6]]

console.log(flattenedTwice);
// expected output: Array [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

- 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) );

console.log(modifiedNumbers);
// expected output: Array [2, 2, 1, 1, 0, 0]
Enter fullscreen mode Exit fullscreen mode

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

See you next week 💙

💖 💪 🙅 🚩
lindaojo
Linda

Posted on November 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related