Массивы являются ссылочными типами, поэтому при сравнении их будет просто сравниваться их ссылки, а не их содержимое.
A быстрый способ (программно) для сравнения содержимоговаши массивы должны привести их в строковое значение JSON.stringify()
и сравнить полученные строки:
const arr1 = [
{id: 1, name: "Australia", code: "AU", isRemoved: false},
{id: 2, name: "France", code: "FR", isRemoved: false}
];
const arr2 = [
{id: 1, name: "Australia", code: "AU", isRemoved: false},
{id: 2, name: "France", code: "FR", isRemoved: false}
];
const arr3 = [
{id: 1, name: "Austria", code: "AS", isRemoved: false},
{id: 2, name: "France", code: "FR", isRemoved: false}
];
console.log(JSON.stringify(arr1) === JSON.stringify(arr2));
console.log(JSON.stringify(arr1) === JSON.stringify(arr3));
Или более быстрый метод, чем строковое преобразование целых массивов , заключается в том, чтобы сначала сравнить длины и, если они совпадают, сравнивать все записи, используя Object.entries()
и Array.every()
.
Это будет работать, если поля ваших записей имеют примитивные типы (не массивы и не объекты), в противном случае вам потребуется рекурсивная версия этого:
const sameEntries = (x, y) => {
const xEntries = Object.entries(x);
if (xEntries.length !== Object.entries(y).length) return false;
return xEntries.every(([k,v]) => y[k] === v);
}
const sameArrays = (arr1, arr2) =>
arr1.length === arr2.length && arr1.every((x, i) => sameEntries(x, arr2[i]));
const arr1 = [
{id: 1, name: "Australia", code: "AU", isRemoved: false},
{id: 2, name: "France", code: "FR", isRemoved: false}
];
const arr2 = [
{id: 1, name: "Australia", code: "AU", isRemoved: false},
{id: 2, name: "France", code: "FR", isRemoved: false}
];
const arr3 = [
{id: 1, name: "Austria", code: "AS", isRemoved: false},
{id: 2, name: "France", code: "FR", isRemoved: false}
];
console.log(sameArrays(arr1, arr2));
console.log(sameArrays(arr1, arr3));