我可以通过指定索引合并两个集合

时间:2013-09-28 10:09:45

标签: underscore.js

c1: [{n: "name 1", r: 152},{n: "name 2", r: 153}, {n: "name 6", r: 157}];

c2: [{n: "name 3", r: 154},{n: "name 4", r: 155}, {n: "name 5", r: 156}];

我有两个集合c1 and c2,如上所述。我需要在index 2处将c2值插入c1。

最终结果应该是这样的。

merged: [{n: "name 1", r: 152},{n: "name 2", r: 153}, {n: "name 3", r: 154},
         {n: "name 4", r: 155}, {n: "name 5", r: 156}, {n: "name 6", r: 157}];

我认为使用union会在开始时合并,而不是在指定的索引处合并。我需要以下划线方式实现这一目标。

2 个答案:

答案 0 :(得分:2)

Array.splice将允许您向数组中添加元素:

  

数组拼接 array.splice(index,howMany [,element1 [,... [,elementN]]])
  更改数组的内容,在删除旧元素时添加新元素。

     

索引
      要开始更改数组的索引。如果大于数组的长度,则不会删除任何元素。如果是否定的,将会   从最后开始那么多元素。

     

的howmany
      一个整数,指示要删除的旧数组元素的数量。

     

element1,...,elementN
      要添加到数组的元素。如果未指定任何元素,则splice只是从数组中删除元素。

要插入元素列表,可以使用_.flatten准备参数:

var c1 = [{n: "name 1", r: 152}, {n: "name 2", r: 152}, {n: "name 6", r: 152}];
var c2 = [{n: "name 3", r: 152}, {n: "name 4", r: 152}, {n: "name 5", r: 152}];

c1.splice.apply(c1, _.flatten([2, 0, c2]));

console.log(c1);

演示http://jsfiddle.net/4cbCy/

或者,如果您希望避免使用_.flatten,则可以使用

var args = c2.slice();
args.unshift(2, 0);
c1.splice.apply(c1, args);

http://jsfiddle.net/4cbCy/1/

答案 1 :(得分:1)

您可以使用vanilla javascript。

var c1 =  [{n: "name 1", r: 152},{n: "name 2", r: 153}, {n: "name 6", r: 157}];
var c2 = [{n: "name 3", r: 154},{n: "name 4", r: 155}, {n: "name 5", r: 156}];
var lastPiece = c1.splice(2)//1 based position, rest of array is returned to last. 
/*c1 now contains only r=152, r=153*/
//For is used for brevity use something else if you have things other then objects
for(var i in c2){c1.push(c2[i])}
c1.push(lastPiece[0])//Since this is an array

OR

   var c1 =  [{n: "name 1", r: 152},{n: "name 2", r: 153}, {n: "name 6", r: 157}];
   var c2 = [{n: "name 3", r: 154},{n: "name 4", r: 155}, {n: "name 5", r: 156}];
   var lastPiece = c1.splice(2)//1 based position, rest of array is returned to last. 
   /*c1 now contains only r=152, r=153*/
   //For is used for brevity use something else if you have things other then objects
   var temp =  c1.concat(c2);
   temp = temp.concat(lastPiece)
   console.log(temp)

有些jsPerf会很有趣。它粉碎了splice.apply