If I have a an array of objects called filteredList
and a function such as :
function buildList(filteredList, p1, p2, p3) {
var resultList = [];
for (var i =0; i < filteredList.length; i++) {
if (filteredList[i].type === 'global' && filteredList[i].p1 === p1 && filteredList[i].p2 === p2 && filteredList[i].p3 === p3)
resultList.push(filteredList[i]);
}
return resultList;
}
What would be the performance difference if instead of looping through my array like I do, I would do something like : filteredList.filter(rebuildList)
rebuildList
being a function checking the same conditions than buildList
Would it do the same ? (Looping through each element)
Can you think of a more optimized and efficient way to do it ? I'm calling a function like buildList
many times in my project and it consumes a great amount of time.
If I have a an array of objects called filteredList
and a function such as :
function buildList(filteredList, p1, p2, p3) {
var resultList = [];
for (var i =0; i < filteredList.length; i++) {
if (filteredList[i].type === 'global' && filteredList[i].p1 === p1 && filteredList[i].p2 === p2 && filteredList[i].p3 === p3)
resultList.push(filteredList[i]);
}
return resultList;
}
What would be the performance difference if instead of looping through my array like I do, I would do something like : filteredList.filter(rebuildList)
rebuildList
being a function checking the same conditions than buildList
Would it do the same ? (Looping through each element)
Can you think of a more optimized and efficient way to do it ? I'm calling a function like buildList
many times in my project and it consumes a great amount of time.
-
What is
filteredList
? It is aarray
orobject
. It is an object then performance will be fasted. – SK. Commented Jul 16, 2015 at 11:45
1 Answer
Reset to default 9You can use the Array.prototype.filter method. Example ing soon
Regarding performance you should read here: Fastest way to find an item in a JavaScript Array