Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to query an array in javascript to get just the items from it I want?

I have an array like this (with just over 3000 objects instead of the 3 here):

items = [{name:'charlie', age:'16'}, {name:'ben', age:'18'}, {name:'steve', age:'18'}] 

What's the best way to return an array with just the objects of people who are 18? So I want:

items = [{name:'ben', age:'18'}, {name:'steve', age:'18'}] 

The best I can think of is this (using jQuery):

newArray = [] $.each(items, function(index, item) {     if(item.age=='18') {         newArray.push(item)     } }) 

Considering that there's 3000 thousand objects, and also that I'll be doing that comparison up to fifty times in one go, that's a lot of looping. Is there a better way?

like image 783
Kenny Flannery Avatar asked Mar 10 '11 09:03

Kenny Flannery


People also ask

How do I query an array in JavaScript?

JavaScript Array find() The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found. The find() method does not execute the function for empty elements.

How do you filter objects from an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

You can use pure javascript

var wanted = items.filter( function(item){return (item.age==18);} ); 

And if your browser does not support the 1.6 version of javascript you can find an implementation of the filter method at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter


Update

Speedwise there is a huge varying (had an error in the test) difference from a normal loop (depending on browser).. Have a look at this little test i made at http://jsperf.com/array-filter-vs-loop/3

like image 125
Gabriele Petrioli Avatar answered Oct 05 '22 22:10

Gabriele Petrioli