1
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像上面这样的集合。我需要将 c2 值插入到 c1 at index 2.

最终结果应该是这样的。

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}];

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

4

2 回答 2

2

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

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

index
开始更改数组的索引。如果大于数组的长度,则不会删除任何元素。如果为负,将从末尾开始那么多元素。

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/

于 2013-09-28T10:39:48.363 回答
1

您可以为此使用香草 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

或者

   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可能很有趣。它压在拼接处。应用

于 2013-09-28T10:37:10.913 回答