skip to Main Content

I have a array of number. I want to filter a new array which have element which index is divided by two

Example:

let arr = [1, 4, 5, 2, 8, 9, 7, 10];

I want filter a 2 new arrays like:

let odd = [1, 5, 8, 7];
let even = [4, 2, 9, 7];

I’ve tried like this but it didn’t work

const odd = arr.filter((i) => {
  return arr[i % 2 === 0];
})

2

Answers


  1. even = arr.filter((i) => { if (i % 2 == 0) return i})
    odd = arr.filter((i) => { if (i % 2 == 1) return i})
    
    Login or Signup to reply.
  2. I understood that you would like the values, but in fact it is the index, to do this, simply receive a second parameter in the filter function, which is the index of the current element:

    arr.filter((e, i) => { return i % 2 === 0; });
    

    previous answer:
    I believe the answer is this:

    arr.filter((e) => {return e % 2 == 0})
    

    when you use the filter function the iteration element is the array position value.
    In your case, the condition:

    i % 2 === 0
    

    returns a boolean value and tries to find a value in the array at that position, so it doesn’t work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search