Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get every second element of array with array methods

for learning purposes I want to get every second element of an array. I succeeded with a for loop:

  const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  function filterEverySecond(arr) {
    let everySecondEl = [];
    for (let i = 0; i < arr.length; i += 2) {
      everySecondEl.push(arr[i]);
    }
    return everySecondEl;
  }

  console.log({
    numbers,
    result: filterEverySecond(numbers)
  });

Now I want to achieve the same without a for loop, but by using array methods (forEach, filter, map or reduce). Can anyone recommend which method would be best here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can do it easily with filter

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const filtered = numbers.filter((_, i) => i % 2 === 0)

console.log(filtered)

you just filter out the elements that have a odd index

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading