Check Object inside an Array using index()

Asked

Viewed 727 times

6

I was solving some challenges of a Javascript course I’m doing, and came across a small problem:

I have the following object array:

var numberObjects = [ 
   {number: 1}, 
   {number: 2}, 
   {number: 3}, 
   {number: 4}, 
   {number: 5}, 
   {number: 6}, 
   {number: 7}, 
   {number: 8}, 
   {number: 9}, 
   {number: 10} 
];

And I need to check for the object {number: 2} within this array, using the method indexOf() and return a message on the console if it is true or false, then I did as follows using the ternary operator:

console.log( numberObjects.indexOf( { number: 2 } ) > -1 ? 'Existe um objeto { number: 2 } em numberObjects!' : 'Não existe um objeto { number: 2 } em numberObjects :(' );

My problem is that even though the object exists { number: 2 } within my array, the return of indexOf() continues to be -1, which means that he is not finding that object within my array, someone would know to inform me why this happens?

I also tried to do by assigning the return of indexOf() a variable, however, without success.

  • 1

    Welcome to Stackoverflow in English. I edited your question to remove the greetings as we usually keep the text as clean as possible to focus on your scheduling question. If you are interested in visiting a part of the site that is not aimed to ask questions can know the [chat]. If you have questions about the operation, rules and procedures of the site visit the [meta] :)

4 answers

8


To use index you would need to test if it is the same object. Note that, just because an object has the same keys and values, doesn’t mean that they are the same object. Therefore:

let obj_1 = {number: 1};
let obj_2 = {number: 1};

console.log(obj_1 === obj_2); // false
console.log(obj_1 == obj_2);  // false

To solve your problem you should keep a reference to the objects and use it in index or use the method findIndex to do the same but with a testing function.

Example with index:

let num_1 = {number: 1},
    num_2 = {number: 2},
    num_3 = {number: 3},
    num_4 = {number: 4},
    num_5 = {number: 5};
  
let objetos = [num_1, num_2, num_3, num_4, num_5];

console.log(objetos.indexOf(num_3));  // 2

Example using findIndex:

var objetos = [ 
   {number: 1}, 
   {number: 2}, 
   {number: 3}, 
   {number: 4}, 
   {number: 5}
];

function find_obj(obj) {
    return obj['number'] === 3;
}

console.log(objetos.findIndex(find_obj)); // 2


It is also worth remembering that if you are not interested in the index where the object was found, but only want to know if it exists in the array the method includes does it for you.

let num_1 = {number: 1},
    num_2 = {number: 2},
    num_3 = {number: 3},
    num_4 = {number: 4},
    num_5 = {number: 5};
  
let objetos = [num_1, num_2, num_3, num_4, num_5];

console.log(objetos.includes(num_3)); // true

  • Thanks Fernando, excellent reply! But the exercise asks me to check using indexOf() this array in particular, because this array statement of the way it is is the resolution of another exercise, so it could not touch the structure.

  • My real doubt is why indexOf() return only -1, if the object exists in my array, and it should return to the position it is in, correct?

  • 1

    If you check the method documentation indexOf you will see that it uses restricted comparison (===)... And as I explained in my answer, even if two objects have the same keys and values, they are distinct objects in memory. This is the reason, and if you want to avoid it you will have to save references to the original objects as shown.

  • 1

    The only reference to the objects in your code are the array itself, IE, to work you should do objetos.indexOf(objetos[2]).. And that doesn’t make any sense. In short, either the question asks for something impossible or you don’t understand the question very well or you lack information to give a correct answer.

6

Using index but with map help. But for the value of your object, and not the object. In this case will return 1, the value of the Indice {number:2}.

numberObjects.map((e) => { return e.number; }).indexOf(2);
  • Great solution Ernesto! This way I don’t need to disassemble the array as my colleague proposed in the other answer, and I can still use the indexOf(). Thank you all so much for helping! D

  • Remember that in this answer you are going through the old array, then creating a new one and only then looking for the value you want. It worked for AP, but be careful to use this technique with too large array.

3

Good because your function is wrong!

According to the documentation

The index() method returns the first index which has the element found in the array, or -1 if is not present.

Do the test by placing numberObjects.indexof( { number: 20 } ), will give the same answer ie there is no { number : 20 } as value of numberObjects array.

How about using this function?

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

arr is the array:

[ 
   {number: 1}, 
   {number: 2}, 
   {number: 3}, 
   {number: 4}, 
   {number: 5}, 
   {number: 6}, 
   {number: 7}, 
   {number: 8}, 
   {number: 9}, 
   {number: 10} 
]

and search would be the object: {number: 1}

  • Thanks Julio! But the exercise I’m doing clearly asks to use the method indexOf(), then could not use this function. :(

  • And the function is not wrong, in another example I did here the return was correct, follow: var arr = [1, 2, 3, 4, 5]; console.log( arr.indexOf( 3 ) ); // vai retornar o índice do item '3' no array, que no caso é '2'

  • Yes, I say the suit

  • what is the mistake in the ternary?

2

Another way would be to convert the array to string with JSON.stringify() and checking with .indexOf() if you have the object in string form:

var numberObjects = [ 
   {number: 1}, 
   {number: 2}, 
   {number: 3}, 
   {number: 4}, 
   {number: 5}, 
   {number: 6}, 
   {number: 7}, 
   {number: 8}, 
   {number: 9}, 
   {number: 10}
];

var tem = JSON.stringify(numberObjects).indexOf('{"number":2}');

console.log(~tem ? 'Existe um objeto { number: 2 } em numberObjects!' : 'Não existe um objeto { number: 2 } em numberObjects :(');

How objects are in format chave + valor numérico, when converting to string the result will be the quotation key and the numeric value just after the colon:

[{"number":1},{"number":2},{"number":3},{"number":4},{"number":5},{"number":6},{"number":7},{"number":8},{"number":9},{"number":10}]

Then just check if the string {"number":2} exists with .indexOf().

In allocating the .indexOf() to the variable tem, by adding before this variable the ~, will return or 0 (if it does not exist, that is to say false) or any number (positive or negative) indicating that there is.

Now an example that the object does not exist:

var numberObjects = [ 
   {number: 1}, 
   {number: 99}, 
   {number: 3}, 
   {number: 4}, 
   {number: 5}, 
   {number: 6}, 
   {number: 7}, 
   {number: 8}, 
   {number: 9}, 
   {number: 10}, 
   {number: 22} 
];

var tem = JSON.stringify(numberObjects).indexOf('{"number":2}');

console.log(~tem ? 'Existe um objeto { number: 2 } em numberObjects!' : 'Não existe um objeto { number: 2 } em numberObjects :(');

Browser other questions tagged

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