Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

You can use filter and check if the index of the current array element is divisible by 2:

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

console.log({
  numbers,
  result: numbers.filter((_, index) => index % 2 === 0)
});

about 4 years ago · Juan Pablo Isaza Report

0

You could use a for each loop like so to get the same desired output:

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

numbers.forEach(number => {
    if (number % 2 != 0) {
        result.push(number);
    }
});

console.log(numbers);
console.log(result);

The modulus operator returns the remainder of the two numbers when divided. For example: 1 % 2 will return 1 as the remainder. So in the if statement we are checking if the number is not divisible by 2.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!