javascript 根据奇数/偶数位置将数组拆分为两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8119941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:21:49  来源:igfitidea点击:

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

javascriptcoffeescript

提问by Running Turtle

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

我有一个数组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]

采纳答案by David says reinstate Monica

You could try:

你可以试试:

var Arr1 = [1,1,2,2,3,8,4,6],
    Arr2 = [],
    Arr3 = [];

for (var i=0;i<Arr1.length;i++){
    if ((i+2)%2==0) {
        Arr3.push(Arr1[i]);
    }
    else {
        Arr2.push(Arr1[i]);
    }
}

console.log(Arr2);

JS Fiddle demo.

JS小提琴演示

回答by Ricardo Tomasi

odd  = arr.filter (v) -> v % 2
even = arr.filter (v) -> !(v % 2)

Or in more idiomatic CoffeeScript:

或者在更惯用的 CoffeeScript 中:

odd  = (v for v in arr by 2)
even = (v for v in arr[1..] by 2)

回答by georg

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:

如果您的目标是现代浏览器,则可以将循环替换为forEach

yourArray.forEach(function(val, i) { 
    result[i & 1].push(val)
})

回答by tokland

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:

[编辑] 现在有_.partition

[xs1, xs2] = _(xs).partition((x, idx) -> idx % 2 == 0)

回答by Ashish Yadav

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)

回答by Abdennour TOUMI

filtersis a non-static & non-built-in Array method , which accepts literal objectof filters functions & returns a literal objectof arrays where the input & the output are mapped by object keys.

filters是一个非静态和非内置数组方法,它接受literal object过滤器函数并返回一个literal object数组,其中输入和输出由对象键映射。

    Array.prototype.filters = function (filters) {
      let results = {};
      Object.keys(filters).forEach((key)=>{
         results[key] = this.filter(filters[key])   
      }); 
      return results;
    }
    //---- then : 
    
    console.log(
      [12,2,11,7,92,14,5,5,3,0].filters({
        odd:  (e) => (e%2),
        even: (e) => !(e%2)
      })
    )

回答by Adrien

Just for fun, in two lines, given that it's been tagged coffeescript :

只是为了好玩,在两行中,因为它被标记为 coffeescript :

Arr1 = [1,1,2,2,3,8,4,6]

[even, odd] = [a, b] = [[], []]
([b,a]=[a,b])[0].push v for v in Arr1

console.log even, odd
# [ 1, 2, 3, 4 ] [ 1, 2, 8, 6 ]

回答by kmARC

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

作为使用下划线链接函数对 tokland 解决方案的单线改进:

xs = [1, 1, 2, 2, 3, 8, 4, 6]
_(xs).chain().groupBy((x, i) -> i % 2 == 0).values().value()

回答by Samir Adel

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

我猜你可以做 2 个 for 循环,以 2 为增量,在第一个循环中从 0 开始,在第二个循环中从 1 开始

回答by lauhub

A method without modulo operator:

没有模运算符的方法:

var subArr1 = [];
var subArr2 = [];
var subArrayIndex = 0;
var i;
for (i = 1; i < Arr1.length; i = i+2){
    //for even index
    subArr1[subArrayIndex] = Arr1[i];
    //for odd index
    subArr2[subArrayIndex] = Arr1[i-1];
    subArrayIndex++;
}
//For the last remaining number if there was an odd length:
if((i-1) < Arr1.length){
    subArr2[subArrayIndex] = Arr1[i-1];
}