Search Matrix index from json value using the index

Asked

Viewed 505 times

4

I have the following matrix:

var usuarios = [
    {nome: "João", id: 1},
    {nome: "Maria", id: 2},
    {nome: "José", id: 3},
    {nome: "Ana", id: 4},
];

I need to return the José user index. I tried using the index as follows:

var usuarios = [
        {nome: "João", id: 1},
        {nome: "Maria", id: 2},
        {nome: "José", id: 3},
        {nome: "Ana", id: 4},
    ];
  
  console.log(usuarios.indexOf({nome: "José", id: 3}))

But I got back -1. I know it’s possible to do this with the for(), but it’s possible to do it with the index?

1 answer

3


Your logic fails because objects are unique, unless they’re references to each other.

Look at these examples:

var a = {};
var b = {};
console.log(a == b); // false

var a = {};
var b = a;
console.log(a == b); // true

So when you use the indexOf it will search the array for an element == and will always give false.

You could make an approach, but it’s not feasible like this:

var u = usuarios.map(JSON.stringify);
console.log(u.indexOf('{"nome":"José","id":3}')); // dá 2

But in this case you compare strings and lose the advantage of using objects. As you suggested the best is with for cycle and with break or return not to need to reach the end, but even then you have to compare values and not the object itself (except as said above that you have a reference in a variable):

function getId(nome) {
    for (var i = 0; i < usuarios.length; i++) {
        if (usuarios[i].nome == nome) return i;
    }
}

console.log(getId('José')); // dá 2

jsFiddle: https://jsfiddle.net/dds3w9o8/

  • 1

    could also use the console.log(usuarios.map(o => o.nome).indexOf("José")) as well as within Function, right? https://codepen.io/flourigh/pen/NWPVeY

  • @flourigh with modern Javascript can do directly usuarios.findIndex(o => o.nome === 'José');

  • in fact, then why preferred the format of his reply?

  • @flourigh because my answer is almost 4 years old and at the time there was no support for this method, it was released with the ES6 version of Javascript.

  • 1

    For, now that I have seen the date, such a question has appeared in the feed for having its answer edited, because someone edits a 4 year answer

Browser other questions tagged

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