Home > Blockchain >  Get every second element of array with array methods
Get every second element of array with array methods

Time:05-09

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?

CodePudding user response:

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

CodePudding user response:

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)
});

CodePudding user response:

You can use filter for index.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log({
    numbers,
    result: numbers.filter((n,i)=>i%2==0)
});

CodePudding user response:

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.

  • Related