3

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.

Ellone
  • 3,022
  • 9
  • 33
  • 61

1 Answers1

5

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

Simpal Kumar
  • 3,331
  • 3
  • 23
  • 47
  • That's what I'm thinking to do, but my question is what will the performance impact be ? Would it do the same : looping through each element, or doest it do something more efficient ? If so, what ? – Ellone Jul 16 '15 at 11:23
  • Updated answer.@Ellone – Simpal Kumar Jul 16 '15 at 11:29
  • I didn't reallly get what are the seek and Object approach in this fiddle http://jsfiddle.net/agup/Y8SBL/10/ They seem to be the more efficient but I don't know how to apply them to my case. It looks like the seeek approach is the use of `indexOf` but in my case I have objects so I can't do it unless I `JSON.stringify` it and it might be even more time consuming to do so – Ellone Jul 16 '15 at 11:42
  • It looks like this article isn't trustable : http://stackoverflow.com/questions/31459395/why-using-for-is-faster-than-some-or-filter – Ellone Aug 04 '15 at 15:00