is there more efficient to getting list of object that contain same property as listed in the array
let x = [{
name: "Apple",
message: {
data: {}
}
},
{
name: "Alienware",
message: {
data: {price: 20 }
}
},
{
name: "dell",
message: {
data: {}
}
},
{
name: "samsung",
message: {
data: {}
}
},
{
name: "Alienware",
message: {
data: {price: 25 }
}
}
];
let nameToCheck = ["HP", "Apple", "Nvidia", "Lenovo", "Acer", "Asus", "Alienware"];
let dataFound = [];
let nameList = {}
x.forEach((element, index) => {
nameList[element.name] = index
})
nameToCheck.forEach((element, index) => {
if (nameList[element] != undefined) {
dataFound.push(x[nameList[element]])
}
})
console.log(dataFound)
The array nameToCheck
can be any data structure.
What i am trying to do is extract the objects that matches with the list of string and that in efficient way in time.
This operation need to happen in very high frequency might be around 40 times a second and list of nameToCheck
is bigger array most probably size of 50.
Is there more time efficient way to do this ? or more nice way of doing this ?
3
Answers
more clear way which achieve the same thing (Set is also indexed so its fast)
btw. in your code you don’t handle cases where you have two items of the same company
You can use a
Set
to store the names to check for. Now all you need to do it just filter the data.Result:
Well, instead of storing indices, you could group them by the
name
Also depending on how critical the loop is you could convert both
reduce
andforEach
to simple loops which are normally faster.If you have to recreate the
nameToCheck
on each iteration, then you could use an object instead of aSet
and a filter for the fastest combo.See https://jsbench.me/g7lm7yni2p/1 for comparison
(keep in mind that result can change if you extract parts outside of the critical loop)
(also keep in mind that results will vary, a lot in some cases, between browsers)