Javascript only removes the first match in an array in a loop

I have an array of exceptions as shown below:

Exclusions: [ID:"233242", Loc:"West", ID:"322234" , Loc:"South"]

I am also an Object nested with an array of objects that might look something like

Schools : [ O: [ ID:"233242" ] , 1:[ ID:"233242"] , 2: [ID :"954944"] ] 

I need to remove from school objects any corresponding array indices with the same identifier, but only for the first match . This means that element 0 should be deleted, but element 1 should still be there. What is the best way to fix my loop:

$.each(Exclusions, function (index, value) {
    var loc = value.Loc;
    var ID = value.ID;
    Object.keys(Schools.District.Pack[loc]).forEach(function (key) {
        //i need to scan through the entire object
        if (Schools.District.Pack[loc].ID === ID) {
            //remove the first match now stop looking
            Schools.District.Pack[loc].splice(key, 1);

            //break ; incorrect
        }
    });
});
+3
source share
1 answer

I would say another search array for remote identifiers and you need something like this

var Exclusions = [{ID:"233242", Loc:"West"}, {ID:"322234" , Loc:"South"}];
var Schools = [{ ID:"233242" } ,{ ID:"233242"} , {ID :"954944"} ];

var removedKeys = [];

$.each(Exclusions, function (index, value) {
    var loc = value.Loc;
    var ID = value.ID;
    Object.keys(Schools).forEach(function (key) {
        //i need to scan through the entire object        
        if ((Schools[key].ID === ID) && (removedKeys.indexOf(ID) == -1)) {
            removedKeys.push(ID);
            //remove the first match now stop looking            
            delete Schools[key];
        }
    });    
});
console.log(removedKeys);
console.log(Schools);

Hope this helps

violin

+1
source

All Articles