Looping through an Array of objects to find an ID in a sub array I have an Array of objects, each which contain their own sub Tags Array, and I need to loop through and find a matching id.

Array: [
    Object {
        tags: [
            { tag_id: 1 },
            { tag_id: 2 }
        ]
        name: name_1
    },
    Object {
        tags: [
            { tag_id: 3 },
            { tag_id: 4 },
            { tag_id: 5 }
        ]
        name: name_2
    }
]


I have a click action when sends in 1 tag from the page to compare and I need to check it's ID to the id of all tags in the larger array.

This is what I have so far which works, but is there a cleaner, simpler more efficient way to do this? With a hashtable perhaps? If so, how?

// I get the large stored Array to compare too:
var tagObjects = TagFactory.retrieveTags();
var index = -1;
var temp_tags = [];

// tagObj is the single tag that is sent from the markup to check:
// Below is what I'm trying to find in the larger array:
console.log(tagObj.tag_id);

// Checking if the large Array has anything
if (tagObjects.length &gt; 0) {

    // I go through and separate the smaller tag Arrays out:
    for (var i = 0; i &lt; tagObjects.length; i++) {
        temp_tags.push(tagObjects[i].tags);
    }

    // Finally I try to find the ID inside of the temp_tags Array:
    for (var i = 0; i &lt; temp_tags[0].length; i++) {
        if (tagObj.tag_id === temp_tags[0][i].tag_id) {
            console.log('found id YEAH!');
            index = 1;
        }
    }
}

// If I found the ID, it means I can remove the tag
if (index !== -1) {
    tagObj.selected = false;
    TagFactory.removeTags(tagObj);
}

// If I did not find the ID, it means I can add it
// Add tag:
else {
I cannot say about AngularJS, but in normal JavaScript I would do something like this:

var tagObjects = TagFactory.retrieveTags();

if (findTag(tagObjects, tagObj.tag_id)) {
    // remove tag
}
else {
    // add tag
}


function findTag(tagObjects, tag_id) {
    return tagObjects
        .reduce(function (total, obj) { return total.concat(obj.tags); }, [])
        .find(function (tag) { return tag.tag_id === tag_id; })
    ;
}


Note that find is a part of upcoming es6 standard. So you might need to use es6-shims (like I do) or write your own version. It's very easy.

Or, if TagFactory.retrieveTags() returns some special structure — shouldn't it also provide findTag method?