3

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
        }
    });
});
2
  • return false will end an each loop, but since you have two of them nested, you will also need to set some kind of flag in the inner loop, that you can check in the outer one to break that off as well. Commented Feb 8, 2014 at 2:20
  • @Cbroe I was thinking of using IndexOf but that's not working plus i think another array scan is too intensive Commented Feb 8, 2014 at 3:11

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I like this approach the problem with delete is that is sets that array element to undefined instead of removing it from the array entirely but it does work.

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.