我有一个数组Arr1 = [1,1,2,2,3,8,4,6]
。
如何根据元素位置的奇数/偶数将其拆分为两个数组?
subArr1 = [1,2,3,4]
subArr2 = [1,2,8,6]
答案 0 :(得分:18)
odd = arr.filter (v) -> v % 2
even = arr.filter (v) -> !(v % 2)
或者更加惯用的CoffeeScript:
odd = (v for v in arr by 2)
even = (v for v in arr[1..] by 2)
答案 1 :(得分:16)
你可以尝试:
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);
答案 2 :(得分:4)
使用嵌套数组会更容易:
result = [ [], [] ]
for (var i = 0; i < yourArray.length; i++)
result[i & 1].push(yourArray[i])
如果您定位的是现代浏览器,则可以使用forEach
替换循环:
yourArray.forEach(function(val, i) {
result[i & 1].push(val)
})
答案 3 :(得分:3)
使用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]现在有_.partition:
[xs1, xs2] = _(xs).partition((x, idx) -> idx % 2 == 0)
答案 4 :(得分:1)
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)
答案 5 :(得分:0)
我猜你可以为2增加2的循环,在第一个循环中以0开始,在第二个循环中以1开始
答案 6 :(得分:0)
没有模运算符的方法:
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];
}
答案 7 :(得分:0)
只是为了好玩,两行,因为它被标记为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 ]
答案 8 :(得分:0)
作为使用下划线链接功能的tokland解决方案的单线改进:
xs = [1, 1, 2, 2, 3, 8, 4, 6]
_(xs).chain().groupBy((x, i) -> i % 2 == 0).values().value()
答案 9 :(得分:0)
filters
是非静态的&amp;非内置Array方法,接受literal object
过滤器功能&amp;返回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)
})
)