indexof does not find element in an array

Asked

Viewed 713 times

5

The indexOf() is returning me -1 even though I have this element, I am doing so:

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 it this way and it’s wrong:

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()

5 answers

7

Let’s print out what you’re having searched:

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 is comparing with a text, it will not work even, an object is never equal to a simple text, they are already of different types, there is no way to be equal.

In the second you are using a member of an object to compare to a text, it turns out that pessoas is not a object is a array with objects within it, each he-ness is an object, but not it as a whole, so it also makes no sense.

If I can change pessoas depending on how 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 in the hand (I prefer it because it is always the fastest of all options, you can test each of them). Something like this:

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 in the Github for future reference.

6

You can use the map to return:

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

function encontrar() {

var retornoIndex = pessoas.map(function(e) { return e.nome; }).indexOf('Pedro');

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

}

encontrar();
  • With index is not possible?

  • @Pedrosilva in your case you have an array that does not contain primitive types. There are a few ways to find the item in the list, this is an option

5


To find objects within an array, use the findIndex, thus:

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.findIndex(x => x.nome === 'Pedro') < 0) {
    console.log('Não existe');
  }else {
    console.log('Já existe');
  }

}

encontrar()

Why doesn’t it work with objects?

Initially, you made the comparison wrong. If you were to compare, you would have to compare with the object inside the Dice, in case, pessoas.indexOf({nome: "Pedro"}); However, this will not work either. That’s why, for javascript, each object is unique, even if its value is identical. A proof? See:

var a = {} // objeto vazio
var b = {} // outro objeto vazio

console.log(a === b); // false

So when you put another object inside, it tries to compare the object inside the indexOf with what is inside the array. It will always return false.

So it is not possible to do with the index, and then you would have to look for other ways to do.

  • So as I understand it, the index only finds elements of which there are no objects inside, that’s it?

  • I will edit with the explanation of why it does not work with objects.

4

Use indexOf would be feasible if your array contained only primitive types in this case use Array.prototype.findIndex()

Note: The findIndex() method returns the index of the first element in matrix satisfying the given test function. Otherwise, returns -1, indicating that no element passed the test. Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

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

function encontrar() {

if(pessoas.findIndex(i => i.nome === "Pedro") < 0) {
    console.log('Não existe');
  }else {
  console.log('Já existe');
  }

}

encontrar()

3

You’re looking for an index where it doesn’t exist. That’s why you can’t find it. The correct one would be this:

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

console.log(pessoas)

function encontrar() {

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

}

encontrar()

The index is looking for "Pedro" only inside the array it is finding only one object with other values. To find values in the object you can use the filter().

Browser other questions tagged

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