0

arr1 is an array of integers. arr2 contains the list of indexes of elements that I wish to remove from arr1.

So this my JS function:

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 i.e 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.

Is there a way to achieve this??and no library should be used,this must be done through Java Script only.

Apologies if the question is ridiculous.. This is for an assignment that I must complete.

3
  • did you have a try, any result / coding?? Commented Nov 1, 2013 at 10:02
  • 1
    if you simply want to avoid use of a third array, then sort arr2 in descending order and then splice arr1 directly. Commented Nov 1, 2013 at 10:06
  • let me add an answer :) Commented Nov 1, 2013 at 10:12

3 Answers 3

1
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);
Sign up to request clarification or add additional context in comments.

Comments

1
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");
}

Comments

0

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...

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);
    } 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.