How to search for a particular object within an array?

Asked

Viewed 47,809 times

7

I need to know if determined Array has a objeto with a certain value in its index.

I tried to use indexOf, but I was unsuccessful.

arr = [];

arr.push({id: 1, nome: 'Wallace'});

arr.indexOf({id: 1}); // -1

How can I search for this object only by the specific index (in this case, the id)?

6 answers

12


If you have an object reference, you can use the indexOf same, which strives for equality (two references are equal only if they point to the same object):

// Não se esqueça de usar var!
var arr = [];
var obj1 = {id: 1, nome: 'Wallace'}
arr.push(obj1);
arr.indexOf(obj1);

Otherwise, you need to check everything in the array until you find your object:

var arr = [];
arr.push({id: 1, nome: 'Wallace'});
for(var i=0; i<arr.length; i++) {
    if(arr[i].id === 1) {
        // achou!
    }
}

or (IE9+):

var arr = [];
arr.push({id: 1, nome: 'Wallace'});
arr.forEach(function(el, i){
    if(el.id === 1) {
        // achou!
    }
});

or even (IE9+):

var arr = [];
arr.push({id: 1, nome: 'Wallace'});
var existe = arr.some(function(el, i){
    return el.id === 1;
});

These are just some of the possible methods. In the other answers you will see that you can also do with filter, map, among other methods.

  • Don’t forget to use var sounded like a subliminal message to me

  • That was the idea :)

5

Another solution is to use the method .map (source:) https://stackoverflow.com/a/16008853/3956218)

The method map() invokes the callback function passed by argument to each element of the Array and returns a new Array as a result.

var log = document.getElementById("menssagemLog");

arr = [];

arr.push({id: 1, nome: 'Wallace'});
arr.push({id: 2, nome: 'Carlos'});
arr.push({id: 3, nome: 'Livia'});

pos = arr.map(function(e) { return e.id; });
log.innerHTML += pos.indexOf(0)// Retorna -1
log.innerHTML += "<br/>"+pos.indexOf(1); // Retorna 0
log.innerHTML += "<br/>"+pos.indexOf(2); // Retorna 1
log.innerHTML += "<br/>"+pos.indexOf(4); // Retorna -1

console.log(log.innerHTML)
<div id="menssagemLog"></div>

3

Because it didn’t work arr.indexOf({id: 1});?

The problem is that when you do arr.indexOf({id: 1}); you are creating a new object and not creating a twin/equal of the other that is already inside the array.

Note that in Javascript this gives false:

var a = {id: 1};
var b = {id: 1};
a == b // false

You need to use something that sticks to that array. For example .filter().

In order to search for object I suggest using an array, or two parameters. Something like that:

function verificar(arr, procurar) {
    var chave = procurar[0];
    var valor = procurar[1];
    return !!arr.filter(function (el) {
        return el[chave] == valor;
    }).length;
}

jsFiddle: http://jsfiddle.net/o041a732/

3

Hello,

I’d do it this way

function procurarIndice(arraySearch, atributo, valor){
   var cont=0;
   var indices=[];
   for(var i in arraySearch){
      var row = arraySearch[i];
      if(row[atributo]==valor){
         indices.push(cont)
      }
      cont++;
   }
   return indices;
}
arr = [];
arr.push({id: 1, nome: 'Wallace'});

procurarIndice(arr,"id",1);

The function would return an array of indices, and to validate whether the expected value exists, it could use an if for the amount

if(procurarIndice(arr,"id",1).length>0){
   ...
}
  • +1. This generates the possibility to pass an array in the third parameter

-2

var id = 1;
var dados = [{id: 1, nome: 'Wallace'},{id: 2, nome: 'Wall'}];  

var i = dados.indexOf(dados.filter((item) =>  item.id == id)[0],0);
console.log(i);

-2

var arr = [{id:1, desc:"1111"},{id:2, desc:"222"},{id:3, desc:"3333"},{id:4, desc:"4444"}];

arr.filter(function( obj ) {
  return obj.id == 1;
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.