chhaya_patel chhaya_patel - 1 month ago 6
Javascript Question

How to remove element from array using javascript

I have 2 array and want to remove the elements of 2nd array as per position numbers on 1st array.

var notexists = []; //value is "1","5","8" on 0,1,2nd position.
var copyrequiredfields = [];//Value is "a","b","c","d","e","f",...
for (var i = 0; i < notexists.length; i++) {
copyrequiredfields.splice(parseInt(notexists[i]), 1);
}


as per example i want to remove 1st 5th and 8th element from copyrequiredfields .
Please suggest some answer.

Answer

Create a new array, iterate the copyrequiredfields, when the index in notexists, ignore it.

example:

var notexist = [1,2,5];
var copyrequiredfields = ['a','b','c','d','e','f','g'];
//create a index map
var index_map = {};
for(var i = 0; i < notexist.length; i++){
    index_map[notexist[i]] = true;
}
//remove the elements
var newarray = [];
for(var i = 0; i < copyrequiredfields.length; i++){
    if(!index_map[i]){
        newarray.push(copyrequiredfields[i]);
    }
}
copyrequiredfields = newarray;