将数组中的多行移动到不同位置的最有效方法

时间:2015-03-11 20:06:39

标签: javascript arrays sorting

例如,我有一个数组

["bob", "mary", "steve", "joe", "phil", "mark", "jon"]

我想转移位置2& 3,并将其插入位置4和4之间。 5.结果数组将是:

["bob", "mary", "phil", "steve", "joe", "mark", "jon"]

有没有办法同时移动这两个元素,而不是单独移动,因为最终会花费更多的性能?

1 个答案:

答案 0 :(得分:1)

我不确定你对我的优化是什么,但是使用splice就是这样:

var arr = ["bob", "mary", "steve", "joe", "phil", "mark", "jon"]; 
var x = arr.splice(2,2);  //remove the two indexes
var args = [3,0].concat(x); //index where to be added is shifted since we removed indexes
Array.prototype.splice.apply(arr, args); //insert back in
console.log(arr);