Sometimes, we want to split an array into two arrays based on odd/even position with JavaScript.
In this article, we’ll look at how to split an array into two arrays based on odd/even position with JavaScript.
How to split an array into two arrays based on odd/even position with JavaScript?
To split an array into two arrays based on odd/even position with JavaScript, we can use the array filter
method.
For instance, we write:
const arr = [1, 1, 2, 2, 3, 8, 4, 6]
const aOdd = arr.filter((_, i) => i % 2 === 1)
const aEven = arr.filter((_, i) => i % 2 === 0)
console.log(aOdd)
console.log(aEven)
to call arr.filter
with (_, i) => i % 2 === 1
to return all the arr
elements with odd indexes.
Likewise, we call arr.filter
with (_, i) => i % 2 === 0
to return all the arr
elements with event indexes.
i
is the index of the element in arr
.
Therefore, aOdd
is [1, 2, 8, 6]
and aEven
is [1, 2, 3, 4]
.
Conclusion
To split an array into two arrays based on odd/even position with JavaScript, we can use the array filter
method.