Ellone
Ellone

Reputation: 3898

Filter performance on objects array

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.

Upvotes: 5

Views: 34661

Answers (1)

SK.
SK.

Reputation: 4358

You can use the Array.prototype.filter method. Example coming soon

Regarding performance you should read here: Fastest way to find an item in a JavaScript Array

Upvotes: 9

Related Questions