[英]Remove several array elements by index and store removed elements
How can I remove multiple items by index and save the removed items.如何按索引删除多个项目并保存删除的项目。 I get the currently selected values from a ListBox (eg
selectedValues = [1, 4, 2]
) and have two arrays actives
availables
.我从 ListBox 获取当前选择的值(例如
selectedValues = [1, 4, 2]
)并且有两个数组actives
availables
。 I try to move the selected elements in an efficient way.我尝试以有效的方式移动所选元素。
That's how I would solve this:这就是我将如何解决这个问题:
var actives = [ "a", "d", "k", "e"] var availables = [ "m", "o", "v" ] var selectedValues = [3, 1] var elementsToMove = [] selectedValues.forEach(i => { elementsToMove.push(actives[i]) }) actives = actives.filter(item => !elementsToMove.includes(item)) availables = availables.concat(elementsToMove); console.log(actives); console.log(availables);
Expected output:预期输出:
actives = [ "a", "k" ]
availables = [ "m", "o", "v", "e", "d"]
Note: The length of the arrays can be very large.注意:数组的长度可能非常大。
A .filter
with an .includes
inside is O(n ^ 2)
.带有
.includes
的.filter
是O(n ^ 2)
。 For very large inputs, this could be an issue.对于非常大的输入,这可能是一个问题。 Consider converting the
elementsToMove
into a Set instead, turning the overall computational complexity to O(n)
.考虑将
elementsToMove
转换为 Set,将整体计算复杂度变为O(n)
。 You can also construct the elementsToMove
array much more concisely by using .map
instead of forEach
followed by push
:您还可以通过使用
.map
而不是forEach
后跟push
来更简洁地构造elementsToMove
数组:
var actives = [ "a", "d", "k", "e"] var availables = [ "m", "o", "v" ] var selectedValues = [3, 1]; const elementsToMove = selectedValues.map(i => actives[i]); const elementsToMoveSet = new Set(elementsToMove); actives = actives.filter(item => !elementsToMoveSet.has(item)) availables = availables.concat(elementsToMove); console.log(actives); console.log(availables);
You could take a single loop and psuh the spliced elements to the other array.您可以采用单个循环并将拼接元素添加到另一个数组。
var actives = [ "a", "d", "k", "e"], availables = [ "m", "o", "v" ], selectedValues = [3, 1]; selectedValues.forEach(i => availables.push(...actives.splice(i, 1))); console.log(actives); console.log(availables);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.