javascript - ¿Cómo comprobar si dos arreglos de objetos tienen el mismo valor de propiedad o no?
tengo dos arreglos y quiero comprobar si todos los IDs son iguales o no
let a = [
{id:0, name:"test0"},
{id:1, name:"test1"}
];
let b = [
{id:0, name:"test0"},
{id:1, name:"test1"}
];
en las matrices anteriores vemos que es igual
y la forma en que me cansé así
JSON.stringify(a) === JSON.stringify(b) => True
Leí que JSON.stringify afecta el rendimiento si tenemos arreglos grandes
¿Entonces hay otra manera de obtener el mismo resultado?
Respuesta #1
const areEqual = (a = [], b = []) => {
// compare length of arrays
if(a.length !== b.length) {
return false;
}
// get sorted lists of ids
const arr1 = a.map(({id}) => id).sort(), arr2 = b.map(({id}) => id).sort();
// iterate over the arrays and compare, if at an index, items mismatch, return false
for(let i = 0; i < arr1.length; i++) {
if(arr1[i] !== arr2[i]) {
return false;
}
}
// if it passes all the items, return true
return true;
}
console.log(
areEqual(
[{id:0, name:"test0"}, {id:1, name:"test1"}],
[{id:0, name:"test0"}, {id:1, name:"test1"}]
)
);Otra solución usando Set:
const areEqual = (a = [], b = []) => {
// compare length of arrays
if(a.length !== b.length) {
return false;
}
// get ids set in b
const idsSetInB = new Set(b.map(({id}) => id));
// iterate over a, and check if the id of an item is not in b
for(let {id} of a) {
if(!idsSetInB.has(id)) {
return false;
}
}
// if it passes all the items, return true
return true;
}
console.log(
areEqual(
[{id:0, name:"test0"}, {id:1, name:"test1"}],
[{id:1, name:"test1"}, {id:0, name:"test0"}]
)
);