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 > 0) {
// I go through and separate the smaller tag Arrays out:
for (var i = 0; i < 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 < 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 {
index = 1;
shouldn't it beindex = i;
? \$\endgroup\$