以最有效的方式剪切和粘贴数组元素

时间:2016-03-09 13:34:57

标签: javascript arrays node.js algorithm mongodb

我知道$pull$push可用于更新mongodb中的数组元素。 但是我想剪切元素并将其粘贴到其他索引。 我想说的是这个;

示例1

我们假设我有

var arr = [a , b, c, d, e];

我想把元素e放在索引0处。现在它应该是

var arr  = [e, a , b, c, d];

有什么变化;

Indices of (a b c d) increase by 1. 

示例2

我们假设我有

var arr = [a , b, c, d, e];

我想剪切元素b并将其粘贴到索引3.现在它应该是

var arr  = [a , c, d, b, e];

有什么变化;

Indices of (c d) decrease by 1. 

如何以最有效的方式处理它?拿存储它的子阵列,然后重新创建arr数组?

我希望以最有效的方式使用较少量的代码来实现。我不知道mongodb的技巧。我检查了the documentation,但无法找到最佳解决方案。你觉得怎么样?

3 个答案:

答案 0 :(得分:1)

第一部分:

var arr  = [a , b, c, d, e];

var item = arr.slice(2,1);

arr.push(item);

第二部分:

var arr = [a , b, c, d, e];

  var items = arr.slice(2,2);

  arr.splice(4,0,items[0], items[1]);

答案 1 :(得分:0)

要限制对特定索引的更改,我相信您可能正在寻找$slice

答案 2 :(得分:0)

鉴于该文件,

> db.history.find({})
{ "_id" : ObjectId("56e02e2c319d15b8fd9c6e69"), "arr" : ["a", "b", "c", "d", "e" ] }

使用以下两个命令,通过$pull从数组中剪切或获取元素,然后通过$push$position

过去或放置它
> db.history.update({}, {$pull: {arr: 'e'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.history.update({}, {$push: {arr: {$each: ['e'], $position: 0}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

结果

> db.history.find({})
{ "_id" : ObjectId("56e02e2c319d15b8fd9c6e69"), "arr" : [ "e", "a", "b", "c", "d" ] }

第二个例子的逻辑相同

> db.history.update({}, {$pull: {arr: 'b'}})
> db.history.update({}, {$push: {arr: {$each: ['b'], $position: 3}}});