split an array into two arrays based on odd/even p

2019-03-25 01:26发布

I have an array Arr1 = [1,1,2,2,3,8,4,6].

How can I split it into two arrays based on the odd/even-ness of element positions?

subArr1 = [1,2,3,4]
subArr2 = [1,2,8,6]

10条回答
爷的心禁止访问
2楼-- · 2019-03-25 01:56
var Arr1 = [1, 1, 2, 2, 3, 8, 4, 6]
var evenArr=[]; 
var oddArr = []

var i;
for (i = 0; i <= Arr1.length; i = i + 2) {
    if (Arr1[i] !== undefined) {
        evenArr.push(Arr1[i]);
        oddArr.push(Arr1[i + 1]);
    }
}
console.log(evenArr, oddArr)
查看更多
走好不送
3楼-- · 2019-03-25 02:05
odd  = arr.filter (v) -> v % 2
even = arr.filter (v) -> !(v % 2)

Or in more idiomatic CoffeeScript:

odd  = (v for v in arr by 2)
even = (v for v in arr[1..] by 2)
查看更多
Melony?
4楼-- · 2019-03-25 02:05

As a one-liner improvement to tokland's solution using underscore chaining function:

xs = [1, 1, 2, 2, 3, 8, 4, 6]
_(xs).chain().groupBy((x, i) -> i % 2 == 0).values().value()
查看更多
看我几分像从前
5楼-- · 2019-03-25 02:07

A functional approach using underscore:

xs = [1, 1, 2, 2, 3, 8, 4, 6]
partition = _(xs).groupBy((x, idx) -> idx % 2 == 0)
[xs1, xs2] = [partition[true], partition[false]]

[edit] Now there is _.partition:

[xs1, xs2] = _(xs).partition((x, idx) -> idx % 2 == 0)
查看更多
ら.Afraid
6楼-- · 2019-03-25 02:07

I guess you can make 2 for loops that increment by 2 and in the first loop start with 0 and in the second loop start with 1

查看更多
放荡不羁爱自由
7楼-- · 2019-03-25 02:12

It would be easier using nested arrays:

result = [ [], [] ]

for (var i = 0; i < yourArray.length; i++)
    result[i & 1].push(yourArray[i])

if you're targeting modern browsers, you can replace the loop with forEach:

yourArray.forEach(function(val, i) { 
    result[i & 1].push(val)
})
查看更多
登录 后发表回答