Categories
JavaScript Answers

How to Extract Elements with an Even Index from an Array?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *