When working with arrays in JavaScript, you might find yourself using only the popular methods like map()
, filter()
, find()
, push()
, and sort()
. And that’s understandable, as these highly useful methods are sufficient for many use cases.
But JavaScript has over 30 array methods, and some of them are lesser-known and rarely used by many JavaScript developers, despite being very powerful and capable of solving real-world problems.
So in the article, we’ll be looking at 7 of these little-known JavaScript array methods. We’ll understand how they work and see how we can use them in practice.
1. copyWithin()
The copyWithin() method copies a part of an array to another position in the same array and returns it, without increasing its length.
For example:
const array = [1, 2, 3, 4, 5];
const result = array.copyWithin(3, 1, 3);
console.log(result); // [1, 2, 3, 2, 3]
You might find the result here confusing if you’re not familiar with this method. To understand how copyWithin()
works let’s take a look at its parameters:
-
target
: is the position in the array to copy the specified part to. -
start
: is the start index of the part that will be copied. -
end
: is the end index of the part that will be copied.
So by passing 3
, 1
, and 3
respectively, we are telling copyWithin()
to take the array elements between index 1
and 3
exclusive, and copy them to another part of the array, starting at index 3
. This means copyWithin()
starts copying the elements 1
and 2
at the place where the element 4
is, replacing 4
and 5
.
Let’s see another example:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// "end" not specified so last array index used
const result = array.copyWithin(0, 5);
// [6, 7, 8, 9, 10, 6, 7, 8, 9, 10]
console.log(result);
Here we are telling copyWithin()
to start copying the numbers 6
, 7
, 8
, 9
, and 10
to the place where 1
is, replacing any successive elements until 10
(the last element) has been copied.
As stated earlier, copyWithin()
will not increase the length of the array, but will stop the copying if it reaches the end of the array.
const array = [1, 2, 3, 4, 5];
// Copy numbers 2, 3, 4, and 5
const result = array.copyWithin(3, 1, 6);
console.log(result); // [1, 2, 3, 2, 3]
2. at()
This method is one of the new ES13 JavaScript features, it provides a cleaner way to access an element from the end of an array.
Instead of writing code like this:
const arr = ['a', 'b', 'c', 'd'];
// 1st element from the end
console.log(arr[arr.length - 1]); // d
// 2nd element from the end
console.log(arr[arr.length - 2]); // c
With at(), we can do this more concisely and expressively, like this:
const arr = ['a', 'b', 'c', 'd'];
// 1st element from the end
console.log(arr.at(-1)); // d
// 2nd element from the end
console.log(arr.at(-2)); // c
We simply pass a negative value of -N
to access the N
th element from the end of the array.
3. reduceRight()
The reduceRight() method works similarly to the more popular reduce() method, with the difference being that the callback function is applied on each value of the array from right to left instead of left to right.
const letters = ['b', 'e', 'a', 'u', 't', 'y'];
const word = letters.reduce((word, letter) => word + letter, '');
console.log(word); // beauty
const wordReversed = letters.reduceRight((word, letter) => word + letter, '');
console.log(wordReversed); // ytuaeb
reduceRight()
repeatedly executes the passed callback function for each element of the array from right to left. The callback we passed here simply concatenates the current element and the accumulator string, eventually resulting in the reversed word.
reduceRight()
can help when you want a list to be expressed from left to right, but evaluated from right to left. Here’s an example of this:
const thresholds = [
{ color: 'blue', threshold: 0.7 },
{ color: 'orange', threshold: 0.5 },
{ color: 'red', threshold: 0.2 },
];
const value = 0.9;
const threshold = thresholds.reduceRight((color, threshold) =>
threshold.threshold > value ? threshold.color : color
);
console.log(threshold.color); // red
4. findLast()
Another new addition to JavaScript in ES13 is the findLast() method, used to search for an item in an array, starting from the last element.
We can use it in cases where we know that finding from the last element might achieve better performance than using the find()
method.
For example, here we’re trying to get the item in the array with the value
property equal to 'y'
. With find()
:
const letters = [
{ value: 'v' },
{ value: 'w' },
{ value: 'x' },
{ value: 'y' },
{ value: 'z' },
];
const found = letters.find((item) => item.value === 'y');
console.log(found); // { value: 'y' }
This works, but as the target object is closer to the tail of the array, we might be able to make this program run faster if we use the findLast()
method to search the array from the end instead:
const letters = [
{ value: 'v' },
{ value: 'w' },
{ value: 'x' },
{ value: 'y' },
{ value: 'z' },
];
const found = letters.findLast((item) => item.value === 'y');
console.log(found); // { value: 'y' }
Another use case for findLast()
is when we have to specifically search the array from the end to get the correct element.
For example, if we want to find the last even number in a list of numbers, find()
would produce a totally wrong result:
const nums = [7, 14, 3, 8, 10, 9];
// gives 14, instead of 10
const lastEven = nums.find((value) => value % 2 === 0);
console.log(lastEven); // 14
But findLast()
will start the search from the end and give us the correct item:
const nums = [7, 14, 3, 8, 10, 9];
const lastEven = nums.findLast((num) => num % 2 === 0);
console.log(lastEven); // 10
5. findLastIndex()
findLastIndex() works like findLast()
, but it returns the index of the found element, rather than the element itself.
In the following example, we use findLastIndex()
to find the index of the last car object in the array with the color red
and remove it.
const carQueue = [
{ color: 'yellow' },
{ color: 'red' },
{ color: 'green' },
{ color: 'red' },
{ color: 'blue' },
];
const lastRedIndex = carQueue.findLastIndex((car) => car.color === 'red');
// Remove car object with splice()
carQueue.splice(lastRedIndex, 1);
/**
[
{ color: 'yellow' },
{ color: 'red' },
{ color: 'green' },
{ color: 'blue' }
]
*/
console.log(carQueue);
6. lastIndexOf()
The lastIndexOf() method returns the last index where a particular element can be found in an array.
const colors = ['a', 'e', 'a', 'f', 'a', 'b'];
const index = colors.lastIndexOf('a');
console.log(index); // 4
We can pass a second argument to lastIndexOf()
to specify an index in the array where it should stop searching for the string after that index:
const colors = ['a', 'e', 'a', 'f', 'a', 'b'];
// Get last index of 'a' before index 3
const index1 = colors.lastIndexOf('a', 3);
console.log(index1); // 2
const index2 = colors.lastIndexOf('a', 0);
console.log(index2); // 0
const index3 = colors.lastIndexOf('f', 2);
console.log(index3); // -1
7. flatMap()
The flatMap() method transforms an array using a given callback function and then flattens the transformed result by one level.
const arr = [1, 2, 3, 4];
const withDoubles = arr.flatMap((num) => [num, num * 2]);
console.log(withDoubles); // [1, 2, 2, 4, 3, 6, 4, 8]
Calling flatMap()
on the array does the same thing as calling map() followed by a flat() of depth 1, but it`s a bit more efficient than calling these two methods separately.
const arr = [1, 2, 3, 4];
// flat() uses a depth of 1 by default
const withDoubles = arr.map((num) => [num, num * 2]).flat();
console.log(withDoubles); // [1, 2, 2, 4, 3, 6, 4, 8]
Conclusion
So we’ve looked at some of the less popular array methods in JavaScript. They might be unknown by many developers, but there is no doubt about their usefulness. You might just need one of them soon.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.
