javascript – "indexOf()" cannot find element in array

Question:

The indexOf() is returning -1 even though I have this element, I'm doing it like this:

pessoas = [];
pessoas.push({"nome": "Pedro"})
pessoas.push({"nome": "João"})
pessoas.push({"nome": "Maria"})
pessoas.push({"nome": "José"})

console.log(pessoas)

function encontrar() {

if(pessoas.indexOf('Pedro') < 0) {
    console.log('Não existe');
  }else {
  console.log('Já existe');
  }

}

encontrar()

I tried as follows and it gives an error:

pessoas = [];
pessoas.push({"nome": "Pedro"})
pessoas.push({"nome": "João"})
pessoas.push({"nome": "Maria"})
pessoas.push({"nome": "José"})

console.log(pessoas)

function encontrar() {

if(pessoas.nome.indexOf('Pedro') < 0) {
    console.log('Não existe');
  }else {
  console.log('Já existe');
  }

}

encontrar()

Answer:

Let's print what you're sending for a search:

 pessoas = []; pessoas.push({"nome": "Pedro"}) pessoas.push({"nome": "João"}) pessoas.push({"nome": "Maria"}) pessoas.push({"nome": "José"}) for (let pessoa of pessoas) console.log(pessoa);

Note that it has objects, it has no texts. In the first example, it's comparing it with a text, it won't work, an object is never the same as a simple text, they are already of different types, there's no way they can be the same.

In the second one is using a member of an object to compare with a text, it turns out that pessoas is not an object 's an array with objects inside it, each element is an object, but not it as a whole, so it doesn't make sense either.

If you can change pessoas depending on how you change it is possible to make the first or the second work, but it would be something quite different. If you change the structure of pessoas one of the ways is to search by hand (I prefer it because it is always the fastest of all options, you can test each one of them). Something like:

 pessoas = []; pessoas.push({"nome": "Pedro"}) pessoas.push({"nome": "João"}) pessoas.push({"nome": "Maria"}) pessoas.push({"nome": "José"}) function encontrar() { for (let pessoa of pessoas) { if (pessoa.nome === 'Pedro') { console.log('Já existe'); return; } } console.log('Não existe'); } encontrar()

I put it on GitHub for future reference .

Scroll to Top