有很多问题/答案涉及这个话题。没有一个符合我的具体情况。希望有人可以帮助:
我有一个索引数组,例如:
var indexes = [24, 48, 32, 7, 11];
以及看起来与此类似的对象数组:
var items = [{
name : "whatever",
selected : false,
loading : true,
progress : 55,
complete : false
},
{
name : "whatever 2",
selected : false,
loading : false,
progress : 100,
complete : true
}];
indexes
数组中的每个整数都对应于 items 数组中对象的实际索引。最后,我有一个变量定义了 items 数组中的新插入位置:
var insertindex = ??
我想要做的是将索引存储在
objects
数组中的 items 数组中的所有 indexes
取出,删除它们,然后最后将它们放回去,并在变量 insertindex
定义的指定索引处彼此相邻。我一直在尝试使用
splice()
,方法是将每个索引处的对象复制到一个临时数组,然后将它们从原始数组中删除,最后循环遍历这个新的临时数组并将它们放回到新位置的原始 items 数组中,但是似乎撞到了精神砖墙,无法正常工作。总而言之,我只是想从 items 数组中取出与 indexs 数组中定义的索引匹配的所有对象,将它们放在一起并在预定义的索引处重新插入它们,回到 items 数组中。
帮助概念可视化 。如果您将该应用程序视为 javascript 文件管理器,则允许重新排序多个不必相邻的文件选择。
indexes
数组定义当前选择,items
数组定义文件列表。最后 rearoderindex
定义了所有选定文件应移动到的新插入位置。编辑:正如这里正确建议的是我现在正在使用的代码:
function reorder(items, indexes, insertindex){
var offset = 0;
var itemscopy = items.slice(0); //make shallow copy of original array
var temparray = new Array(); // create temporary array to hold pulled out objects
//loop through selected indexes and copy each into temp array
for(var i=0, len=indexes.length; i<len; i++){
array[i] = itemscopy[self.cache.selecteditems[i]];
}
//remove all selected items from items array
for(var i=0, len=indexes.length; i<len; i++){
items.splice(indexes[i], 1);
}
//finally loop through new temp array and insert the items back into the items array at the specified index, increasing the index each iteration using the offset variable.
for(var i=0, len=temparray.length; i<len; i++){
items.splice((insertindex+offset), 0, array[i]);
offset++;
}
}
我知道这非常可怕,并且不需要循环三遍。但是我一直在尝试许多不同的方法,一些在一个方向重新排序时起作用,一些在另一个方向上重新排序,但根本没有。我想我会在以后优化该功能,一旦我让它准确工作。
我敢肯定我一定是在做一些非常愚蠢或完全忽视的事情,但对于我的生活,我现在无法弄清楚是什么。
最佳答案
您可以使用 .splice()
函数向数组添加元素,以及从中删除项目。一般原则是:
indexes
,移除该索引处的元素(调整移除项目的数量)并将其存储在 removedItems
数组 removedItems
数组添加回所需的索引 执行此操作的代码如下所示:
var removedItems = [];
// sort indexes
indexes.sort(function(a, b) {
if(a < b) return -1;
else if(b < a) return 1;
return 0;
});
for(var i = 0; i < indexes.length; i++) {
var index = indexes[i];
removedItems.push(items.splice(index - removedItems.length, 1));
}
var insertIndex = 1;
items.splice.apply(items, [insertIndex, 0].concat(removedItems));
看看 this jsFiddle demo 。
关于javascript - 在javascript中重新排序数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15619667/