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
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:
previous answer:
I believe the answer is this:
when you use the filter function the iteration element is the array position value.
In your case, the condition:
returns a boolean value and tries to find a value in the array at that position, so it doesn’t work.