Edward
Edward

Reputation: 3081

javascript only remove first match in array in loop

I have an array of Exclusions like below:

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

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

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

I need to delete from the schools object any matching array indices with the same ID but only for the first match. That means element 0 should be removed, but element 1 should still be there. What's 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
        }
    });
});

Upvotes: 3

Views: 1385

Answers (1)

code-jaff
code-jaff

Reputation: 9330

I'd say having another lookup array for removed IDs, and you'll 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 would help

fiddle

Upvotes: 1

Related Questions