Home > Web Front-end > JS Tutorial > How to Find the Difference Between Two JavaScript Arrays of Objects?

How to Find the Difference Between Two JavaScript Arrays of Objects?

Susan Sarandon
Release: 2024-12-18 01:12:09
Original
455 people have browsed it

How to Find the Difference Between Two JavaScript Arrays of Objects?

Determining the Difference Between Arrays of Objects in JavaScript

The concept of contrasting two arrays of objects often arises when comparing data sets. This article explores a method to extract distinct elements between two arrays, ensuring preservation of specific object properties.

Consider the following input arrays:

Result 1:
[
    { value: "0", display: "Jamsheer" },
    { value: "1", display: "Muhammed" },
    { value: "2", display: "Ravi" },
    { value: "3", display: "Ajmal" },
    { value: "4", display: "Ryan" }
]

Result 2:
[
    { value: "0", display: "Jamsheer" },
    { value: "1", display: "Muhammed" },
    { value: "2", display: "Ravi" },
    { value: "3", display: "Ajmal" }
]
Copy after login

The desired outcome is the difference between these arrays, which would yield an array containing only the unique element from Result 1:

[
    { value: "4", display: "Ryan" }
]
Copy after login

JavaScript offers native methods that can elegantly accomplish this task. By defining a comparison function that evaluates the equality of objects based on their properties, you can leverage the onlyInLeft() function to identify elements that solely exist in the left (original) array. This same process can be applied to the right (new) array.

const isSameUser = (a, b) => a.value === b.value && a.display === b.display;

const onlyInA = onlyInLeft(result1, result2, isSameUser);
const onlyInB = onlyInLeft(result2, result1, isSameUser);

const result = [...onlyInA, ...onlyInB];
Copy after login

The result variable will subsequently contain an array with the distinction between the two input arrays. This approach provides a flexible solution to compare arrays of objects while preserving specific properties for comparison.

The above is the detailed content of How to Find the Difference Between Two JavaScript Arrays of Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template