javascript – "indexOf()" does not find element in an 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 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 asking for:

 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 you are comparing with a text, it will not work anyway, an object is never equal to a simple text, they are already of different types, there is no way to 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 it'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 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's always the fastest of all the 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