[英]Removing array elements by index
arr1 is an array of integers. arr1是一个整数数组。 arr2 contains the list of indexes of elements that I wish to remove from arr1.
arr2包含我希望从arr1中删除的元素的索引列表。
So this my JS function: 这是我的JS功能:
function deletion()
{
var arr3=[];
var arr1= [2,3,4,5,6,7,8,11,22];
console.log(arr1);
var arr2 = [4,0,1];
for(var i=0;i<arr2.length;i++)
{
arr3.push(arr1[arr2[i]]);
}
for(var j=0;j<arr3.length;j++)
{
arr1.splice(arr1.indexOf(arr3[j]),1);
}
console.log(arr1,"array1");
}
This works fine but now the requirement is : I need to use more efficient way . 这很好但现在要求是:我需要使用更有效的方法。 arr3 should not be used ie I don't want to use another new array and push elements into it and then loop through it.I want this to be achieved without using new array.
不应该使用arr3,即我不想使用另一个新数组并将元素推入其中,然后循环遍历它。我希望在不使用新数组的情况下实现这一点。
Is there a way to achieve this??and no library should be used,this must be done through Java Script only. 有没有办法实现这个?并且不应该使用任何库,这必须仅通过Java Script完成。
Apologies if the question is ridiculous.. This is for an assignment that I must complete. 如果这个问题很荒谬,那就道歉了。这是我必须完成的任务。
var arr1= [2,3,4,5,6,7,8,11,22];
var arr2 = [4,0,1];
arr2 = arr2.sort().reverse();
for(var i = 0; i < arr2.length; i++){
arr1.splice(arr2[i],1);
}
console.log(arr1);
function deletion()
{
var arr1= [2,3,4,5,6,7,8,11,22];
console.log(arr1);
var arr2 = [4,0,1];
arr2 .sort(function(a,b){return a>b?-1:1});
for(var i=0;i<arr2.length;i++)
{
arr1.splice(arr2[i],1);
}
console.log(arr1,"array1");
}
You can use Array.splice
to this effect, it may not be appropriate in this form due to the double loop complexity but you get the idea... 您可以使用
Array.splice
来实现此效果,由于双循环复杂性,它可能不适合这种形式,但您明白了......
var arr1= [2,1,3,4,5,6,7,8,11,22],
arr2 = [4,0,1];
for (var i in arr1) {
for (var j in arr2) {
if (arr1[i] == arr2[j])
arr1.splice(i, 1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.