I come up with this solution to compare a string to an array of object. However, I don't think this is the best solution. Any suggestion on how to make this function perform better for large array of object?
var a = "blAh";
var b = [{
"tag": "tag1",
"icons": ["blah"]
}, {
"tag": "tag2",
"icons": ["Blah", "apple", "banana", "bLaH"]
}];
// Desired output "tag1, tag2"
function getTitle(tags, icon) {
let arr = [];
for (var i = 0; i < tags.length; i++) {
tags[i].icons.forEach(elem => {
if (icon.toLowerCase() === elem.toLowerCase()) {
if (!arr.includes(tags[i].tag)) {
arr.push(tags[i].tag);
}
}
});
}
return arr.join(', ');
}
console.log(getTitle(b, a));
icon = icon.toLowerCase()before entering the loop, but what is your actual issue? Lookup speed can be greatly increased using an index, but building the index is additional overhead. You could also build an index of stored values so instead of!arr.includes(tags[i].tag)you'd have a property lookup:!(tags[i].tag in seenValues), etc.icon.toLowerCase()at the very begining of the function (store it in a variable so you won't call it over and over again). If you are looking for an improvment in readability not performance, then usereduce,filterandconcat, ...