Best way to know if an object array has the same values, even at different positions

Asked

Viewed 41 times

-4

I would like a help for a function, where I have to know if two objects have the same values, even if in different positions.

In this case they have the same values. I’ve seen how to do with arrays, which is to use a sort and then compare the values, but what if they are objects? Do you know any method?

**Updating ** Personal I apologise, I saw now the answers and edited.

Example:

let arr1 = [{id:1, idade:5},{id:2, idade:10},{id:3, idade:15},{id:4, idade:20}];
let arr2 = [{id:4, idade:20},{id:1, idade:5},{id:3, idade:15},{id:2, idade:10}];

Thank you!

  • But in case you would have an Object Array, right?

  • You will need a property that is able to distinguish objects, as a unique identifier for each object (usually named id). Please [Dit] your question to clarify your problem a little more. And about the sort, there are more efficient solutions.

1 answer

-1

Well, the simplest way would be to loop through one of the arrays and use the method .include(), that returns a Boolean.


let arr1 = [1,2,3,4];
let arr2 = [4,2,1,3];

function check(primeira_array, segunda_array){

  for(let i = 0; i < primeira_array.length-1; i++){

    if(segunda_array.includes(primeira_array[i])){

       return arr1[i]; /// o que fazer caso o método retorne true, no exemplo retornar o valor de dentro da array, seja número, objeto, etc...
    }
  }
}


console.log(check(arr1, arr2));

In the example you can access the number that repeats with, for example: var item = check(arr1, arr2);

  • As far as I understand it, he has already managed to do this part. He wants to know how to do this in an array of objects. The problem is that we cannot give a concrete answer since the PA did not mention which property can be used to make the distinction reasonably.

  • Can you understand if he wants to compare values, parameters, object nomenclature?

  • 1

    Yeah, you don’t know. : / The most you can understand of the question is that he has already managed to do this check for arrays of primitives. But could not do with object array. The problem is that it does not indicate for certain as intends to make the comparison between each object.

Browser other questions tagged

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