Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

516
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda