JavaScript在特定索引处添加和删除多个列表值

5

我有一个代码像这样:

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [1, 3] // ball and dog
var to = 5 // fish

for(var i in index){
  console.log(index[i])
  var local_data = data
  data.splice(to, 0, data.splice(index[i]), 1)
}

console.log(data)
console.log(index)

JsFiddle

这里的var index = [1,3]是要设置的数据的索引值。

我想要的是,在fish之后设置balldog的值,其余保持原有顺序。

插入后,我希望index的值根据balldog的新位置进行更改,即[4,5]

更新

最终我想要的结果是:console.log(data)应该返回

["apple", "cat", "elephant", "fish", "ball", "dog", "gorilla"]

console.log(index) 应该输出:

[4, 5] // new value of ball and dog

你能重新表达一下你想要的最终结果吗?也许包括你希望代码结束时变量的状态? - user01
@user01,请检查更新。 - gamer
4个回答

1

你可以用这种方式来实现。

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [4, 5]; 
var to = 2  ;

var arrTemp = [];

data.forEach(function(val,key){

  if(index.indexOf(key)!=-1){

    data.splice((to+1),0,data[key]);
    to++;
    delete data[key];

  }
})
data = data.filter(function(val){ return val != undefined }); 

console.log(data)


UPDATE : 

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [ 2,3];
var to = 5 ;
var arrTemp = [];

data.forEach(function(val,key){

  if(index.indexOf(key)!=-1){    
    arrTemp.push(data[key]);
    delete data[key];

  }
})

to=to+1;
for(var pos=0;pos<index.length;pos++){
   data.splice(to++,0,arrTemp[pos])
}
data = data.filter(function(val){ return val != undefined }); 
 

JsFiddle


有一些问题...如果我输入 index = [2, 3],它在第 2 个索引处给出了 null..并且在删除元素后,index 的值没有更新。 - gamer
如果我输入 [2, 4] 这样的值,它会给出正确的结果,但是在输入 [2, 3] 时会出现错误。 - gamer
非常感谢。如何使用新值更新索引? - gamer
如果您删除了n个项目,则需要从每个索引arr元素中减去n。 - RIYAJ KHAN
你正在处理同一个数组吗? - RIYAJ KHAN
显示剩余3条评论

1
这是一个棘手的问题,但解决它很有趣。
这是我的解决方案,可能不是最有效的,但它完成了工作。
var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"];
var output = [];
var index = [1, 3]; // ball and dog
var to = 5; // fish

var extractValues = [];
index.forEach(function(i){
  extractValues.push(data[i]);
});

var valueToPutAfter = data[to];

// Put the value first
data.forEach(function(element) {
  if (element === valueToPutAfter) { // found element to push after
    output.push(element);
    extractValues.forEach(function(value){
      output.push(value);
    });
  }
  else {
    output.push(element);
  }

});


// Mark the position that needs to be deleted as null
var prevDelIndex = 0;
index.forEach(function(i){
  output[i] = null;
});

// delete the elements
output.forEach(function(element, index) {
  if (element == null) {
      output.splice(index, 1);
  }
});

console.log(output);
console.log(output.indexOf("ball"));
console.log(output.indexOf("dog"));

我已将您的问题分解成几个小问题,并按系统化的方式处理它们。
我的方法是首先循环遍历数据数组并推送所有元素(包括新元素)。然后再次遍历列表,并将在“位置,变量索引数组”中找到的元素标记为空并删除它们。
算法步骤:
1. 首先确定需要从数组(data)中提取什么。 2. 类似地,确定需要放在其后的元素。 3. 循环遍历初始数组以查找在第(2)点中提到的元素,然后开始将需要放在其后面的任何内容放在其后面。 4. 现在,您将拥有一个由原始值和新项目组成的数组。 5. 使用垃圾回收概念,我遍历新数组并将“要删除”的元素标记为null。这样我就知道哪个元素稍后要用splice删除。 6. 再次循环遍历新数组,寻找标记的元素(null)并将它们删除。
现在,您将得到您想要的结果。
输出:

[ '苹果', '猫', '大象', '鱼', '球', '狗', '大猩猩' ]

indexOf '球' = 4

indexOf '狗' = 5


1

现在这个功能可以在原地使用,并使用一些偏移指示器,如left用于提取值和right用于插入值。

完成后,索引是基于left偏移量计算的。

Example for from = [1, 3, 6], to = 5

           from              from               to               from      offset
    0        1        2        3        4        5        6        7     left right
-------- -------- -------- -------- -------- -------- -------- -------- ----- ----- 
  apple   [ball]     cat     [dog]  elephant  (fish)   gorilla [banana]   0     0
  apple     cat     [dog]  elephant  (fish)   [ball]   gorilla [banana]  -1     0
  apple     cat   elephant  (fish)   [ball]    [dog]   gorilla [banana]  -2     0
  apple     cat   elephant  (fish)   [ball]    [dog]  [banana]  gorilla  -2     1

function juggle(data, from, to) {
    var left = 0,
        right = 0;

    from.forEach(function (a) {
        if (a + left < to) {
            data.splice(to, 0, data.splice(a + left, 1)[0]);
            left--;
        } else {
            right++;
            data.splice(to + right, 0, data.splice(a, 1)[0]);
        }
    });
    from.forEach(function (_, i, a) { a[i] = to + left + i + 1; });
}

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla", "banana"],
    index = [1, 3, 7], // ball dog banana
    to = 5;            // fish
   
juggle(data, index, to);
console.log(data);
console.log(index);

data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla", "banana"];
index = [4, 5];        // elephant fish
to = 2;                // cat

juggle(data, index, to);
console.log(data);
console.log(index);


1

哇,好问题,我真的很享受通过这个问题的方式进行编程。我采用了函数方法,因为这还没有被尝试过:

var data = ["apple", "ball", "cat", "dog", "elephant", "fish", "gorilla"]
var index = [2, 3] // ball and dog
var to = 5 // fish

var moveItemsToPosition = function (data, indices, to) {
  var movingItems = [];
  var after = data[to + 1];

  for (var i = 0 ; i < indices.length; i++) {
    // takes out the items that will be moved form the original array
    movingItems.push(data[indices[i] - i]);
    data.splice(indices[i] - i, 1);
  }

  // finds the new position of the item to move next to
  var pos = data.indexOf(after);
  var data2 = data.slice(pos, data.length);
  // join the items that will be moved
  data = data.slice(0, pos).concat(movingItems);
  data = data.concat(data2);
  // update the indices
  for (var i = 0 ; i < indices.length; i++) {
    // get the new indices
    indices[i] = data.indexOf(movingItems[i]);
  }

  return [data, indices];
}

console.log(moveItemsToPosition(data, index, to));

它返回更新后的数组和新的索引。您可以根据需要删除此内容。基本上,算法首先取出需要移动的项目,然后找到需要移动的项目旁边的项目,并将其放置在那里(借助精美的JS)。希望这可以帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接