将对象数组合并到每个包含3个对象的数组数组

时间:2012-10-23 15:14:31

标签: javascript algorithm

我有许多对象的以下JavaScript数组:

[
    {...},
    {...},
    {...},
    .
    .
    .
    .
    .
    {...},
    {...}
]

我想将数组转换为3个对象的行,如下所示:

[
    [ {...}, {...}, {...} ],
    [ {...}, {...}, {...} ],
    [ {...}, {...}, {...} ],
    .
    .
    .
    [ {...}, {...}, {...} ],
    [ {...}, {...}, {...} ]
]

最好的方法是什么?

4 个答案:

答案 0 :(得分:3)

另一个片段(改编自@Florent)

var result = [];

do {
   result.push( data.splice( 0, 3 ) )
} while( data.length );

答案 1 :(得分:2)

使用for循环:

var i = 0
  , n = data.length
  , result = [];

for (; i < n; i += 3) {
  result.push([data[i], data[i + 1], data[i + 2]]);
}

答案 2 :(得分:2)

你可以用循环来做。这将获取数组items并创建数组result

var result = [];
var line;
for (var i = 0; i < items.length; i++) {
  if (i % 3 == 0) {
    line = [];
    result.push(line);
  }
  line.push(items[i]);
}

(即使源数组不能被三个整除,这种循环方式也能正常工作。)

答案 3 :(得分:0)

另一种选择:)

var result = arr.reduce(
    function(prev, curr, index) { 
        if(index > 1) { 
            if(prev[prev.length-1].length == 3) 
                prev.push([]); 
            prev[prev.length-1].push(curr); 
            return prev; 
        }
        return [[prev, curr]]; 
    }
);