Sometimes, we want to extract elements with an even index from an array.
In this article, we’ll look at how to extract elements with an even index from an array.
Extract Even Elements of an Array
To extract elements with an even index from an array., we can use the array filter
instance method.
For instance, we can write:
const arr = [4, 5, 7, 8, 14, 45, 76];
const filtered = arr.filter((element, index) => {
return (index % 2 === 0);
});
console.log(arr)
to call filter
with a callback that has index
as the 2nd parameter.
We return index % 2 === 0
to filter out all the elements that have odd indexes.
Therefore, filtered
is [4, 5, 7, 8, 14, 45, 76]
.
Conclusion
To extract elements with an even index from an array., we can use the array filter
instance method.