Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

248
Vistas
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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar

0

Get matched item and items using find() and filter() method

If you want first matched single item, use find() method which returns single object.

If you want all matched , use filter() method which returns array of objects.

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

let all = items.filter(item=> item.age==='18')
console.log(all);

let single = items.find(item=> item.age==='18')
console.log(single);

over 4 years ago · Santiago Trujillo Denunciar

0

If you're going to do the search often it may be best to keep a version of your data in a form that is quick to access. I've used underscore.js (http://documentcloud.github.com/underscore/) to make it easy for myself, but this code here will create an object that holds your data indexed by the age field.

You end up with something that looks like this:

{
    "16": [
        {
            "name": "charlie",
            "age": "16"
        }
    ],
    "18": [
        {
            "name": "ben",
            "age": "18"
        },
        {
            "name": "steve",
            "age": "18"
        }
    ]
}

The code:

var itemsByAge = _(items).reduce(function(memo, item) {
    memo[item.age] = memo[item.age] || [];
    memo[item.age].push(item);
    return memo;
}, {});

alert(JSON.stringify(itemsByAge["18"]));
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda