JavaScript Two Arrays Difference Checker


This online utility helps you easily compare two arrays and identify their unique elements. Whether you are debugging code, analyzing data sets, or learning about array operations, this tool makes it simple to spot the differences between arrays.

Find Array and Object Differences Made Easy

Finding the differences between two arrays or arrays of objects is a frequent challenge in programming. Whether you are comparing simple arrays or arrays containing nested objects, our JavaScript function simplifies the task. This versatile solution is designed to deliver accurate results for a wide range of data types and structures.

Live Two Arrays Difference Checker Tool

Try our Live Array Difference Testing Tool to compare arrays and arrays of objects in real time. Just input your data, and the tool will instantly compute the differences, showing items unique to each array. Perfect for debugging, data validation.

  1. Enter your first array in JavaScript format (e.g., ["a", "b", "c", 1, 2, 3])
  2. Enter your second array in the same format
  3. Click the "Check Difference" button to compare
  4. View the results instantly

You can add arrays or arrays of objects, And drop or upload file.

Options:

?Makes string comparisons case-sensitive ['hello', 'Hello']
?Removes leading/trailing whitespace from strings '  hello'
?Allows comparison across different types (e.g., '1' vs 1)
?Considers array element order in comparison

Select array type:

Choose between a Primitive Array or an Array of Objects. When working with an Array of Objects, you can either ignore specific keys during the comparison or focus on comparing objects based on the specific keys you provide.

Results:

Unique in first array

0

Unique in second array

1

Total Unique

1

Common Elements

11

Similarity

92%

Only in first array:

Only in second array:

How the Function Handles Arrays and Objects

Our function supports both primitive and nested objects, ensuring accurate comparisons even for complex data. By performing a deep comparison, it detects unique items in each array while maintaining high performance.

🔒 No Data Collection Your Data Stays Private

We respect your privacy. We do not collect, store, or transmit any data you provide (arrays, objects, or code).

How It Works

  • The tools on this website operate client-side, meaning all computations are performed in your browser.
  • No user input is sent to our servers or stored in any database.
  • Your data remains under your control at all times.

Supported Array Types

  1. Primitive Arrays:

    • Example: [1, 2, 3] vs [2, 3, 4].
    • Identifies unique elements between arrays of numbers, strings, or booleans.
  2. Object Arrays:

    • Example: [{ id: 1, name: 'Alice' }] vs [{ id: 2, name: 'Bob' }].
    • Compares object properties deeply and identifies differences.
  3. Mixed Arrays:

    • Example: [1, { id: 2 }] vs [2, { id: 2 }].
    • Handles arrays containing a mix of primitives and objects.
  4. Nested Arrays:

    • Example: [[1, 2], [3, 4]] vs [[3, 4], [5, 6]].
    • Compares arrays within arrays recursively.

JavaScript Function Find Two Arrays Difference Checker

Here is the JavaScript function to check the difference between two arrays. This function will return an object with two arrays: items that are unique to the first array and items that are unique to the second array.

JavaScript
/**
 * Compare two arrays and return their differences.
 */
const findArrayDifference = (array1, array2) => {
    // Convert arrays to Sets for faster lookups
    const set1 = new Set(array1);
    const set2 = new Set(array2);

    // Find items unique to the first array
    const onlyInFirst = array1.filter(item => !set2.has(item));

    // Find items unique to the second array
    const onlyInSecond = array2.filter(item => !set1.has(item));

    return {
        onlyInFirst,
        onlyInSecond
    };
};

Example Usage:

JavaScript
// Example usage:
const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];

const result = findArrayDifference(array1, array2);
console.log('Only in first array:', result.onlyInFirst); // [1, 2]
console.log('Only in second array:', result.onlyInSecond); // [5, 6]

JavaScript Function For Arrays Or Arrays Of Objects Comparison

Here is a modern JavaScript function to help you identify the differences between two arrays or arrays of objects. The function efficiently handles deep comparisons to ensure precise results.

Below is the code snippet for a function that finds the differences between two arrays while ignoring specified keys.

JavaScript
/*
* Finds differences between two arrays of objects with deep comparison
*/
const findArrayObjectDifference = (array1, array2, ignoredKeys = []) => {
    // Helper function to deep compare two values
    const isEqual = (value1, value2, visited = new WeakMap()) => {
    	// Handle primitive types and functions
        if (value1 === value2) return true;
        if (typeof value1 !== 'object' || value1 === null ||
            typeof value2 !== 'object' || value2 === null) {
            return false;
        }
        if (visited.has(value1)) return visited.get(value1) === value2;
        visited.set(value1, value2);
        const keys1 = Object.keys(value1).filter(key => !ignoredKeys.includes(key));
        const keys2 = Object.keys(value2).filter(key => !ignoredKeys.includes(key));
        if (keys1.length !== keys2.length) return false;
        return keys1.every(key => isEqual(value1[key], value2[key], visited));
    };

    // Check if an item exists in the other array
    const isInArray = (item, array) => array.some(otherItem => isEqual(item, otherItem));

    // Find unique items
    const onlyInFirst = array1.filter(item => !isInArray(item, array2));
    const onlyInSecond = array2.filter(item => !isInArray(item, array1));

    return { onlyInFirst, onlyInSecond };
};

Example Usage:

JavaScript
// Example usage:
const array1 = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
];

const array2 = [
    { id: 3, name: 'Charlie' },
    { id: 4, name: 'David' },
    { id: 2, name: 'Bob' }
];

const result = findArrayObjectDifference(array1, array2);
console.log('Only in first array:', result.onlyInFirst); // [{ id: 1, name: 'Alice' }]
console.log('Only in second array:', result.onlyInSecond); // [{ id: 4, name: 'David' }]

Example Ignoring Specific Keys:

JavaScript
const firstArray = [{ id: 1, name: 'Babu', age: 25, place: 'India' }];
const secontArry = [{ id: 1, name: 'Babu', age: 30, place: 'Italy' }];
const ignoredKeys = ['age', 'place'];
const result2 = findArrayObjectDifference(firstArray, secontArry, ignoredKeys);
console.log(result2);
// Output: { onlyInFirst: [], onlyInSecond: [] }

JavaScript Function to Find Array Differences by Specific Keys

This utility function is a powerful tool for comparing and filtering arrays of objects in JavaScript. With its flexibility and focus on specific keys.

JavaScript
/**
 * Finds differences between two arrays based on specified keys
 */
const findArrayDifferenceWithSpecificKeys = (array1, array2, specificKeys = []) => {
    // Input validation
    if (!Array.isArray(array1) || !Array.isArray(array2)) {
        throw new Error("Both inputs must be arrays.");
    }

    if (!Array.isArray(specificKeys)) {
        throw new Error("specificKeys must be an array.");
    }

    // Deep comparison of objects based on specific keys
    const compareByKeys = (obj1, obj2) => {
        // Handle primitive comparisons
        if (typeof obj1 !== 'object' || obj1 === null) return obj1 === obj2;
        if (typeof obj2 !== 'object' || obj2 === null) return false;

        // Filter and compare only specified keys
        return specificKeys.length === 0 ||
            specificKeys.every(key => {
                // Check if key exists in both objects
                const hasKey1 = key in obj1;
                const hasKey2 = key in obj2;

                // If key doesn't exist in both, they're not equal
                if (hasKey1 !== hasKey2) return false;

                // Compare values if key exists
                return hasKey1 ? obj1[key] === obj2[key] : true;
            });
    };

    // Find unique items in each array
    const onlyInFirst = array1.filter(
        item => !array2.some(other => compareByKeys(item, other))
    );

    const onlyInSecond = array2.filter(
        item => !array1.some(other => compareByKeys(item, other))
    );

    return {
        onlyInFirst,
        onlyInSecond
    };
};

Example Usage:

JavaScript
// Example usage:
const array1 = [
    { id: 1, name: "Sali", age: 25 },
    { id: 2, name: "Boby", age: 30 },
];

const array2 = [
    { id: 1, name: "Sali", age: 26 },
    { id: 3, name: "Surya", age: 35 },
];

const specificKeys = ["id", "name"];

const result = findArrayDifferenceWithSpecificKeys(array1, array2, specificKeys);
console.log(result);
// Output:
// {
//   onlyInFirst: [{ id: 2, name: "Boby", age: 30 }],
//   onlyInSecond: [{ id: 3, name: "Surya", age: 35 }]
// }