How to Compare Jagged Arrays using Lodash ?

Jagged arrays, or arrays of arrays, pose a unique challenge when it comes to comparison, especially when order doesn’t matter.

Below are the approaches to compare jagged arrays using Lodash:

Table of Content

  • Sorting and Comparing
  • Converting to Sets and Comparing

Run the below command to install Lodash:

npm i lodash

Sorting and Comparing

In this approach, utilize Lodash to compare jagged arrays by first sorting the arrays and then checking for equivalence using _.isEqual(). Arrays array1 and array2 are sorted using _.sortBy() to ensure consistent comparison. The sorted arrays are then compared for equality, and the result is logged to the console, which returns true in this case.

Example: The below example shows how to Compare Jagged Arrays using Lodash with Sorting and Comparing.

JavaScript
const _ = require("lodash");

const array1 = [
    ["a", "b"],
    ["b", "c"],
];
const array2 = [
    ["b", "c"],
    ["a", "b"],
];

// Sort the arrays before comparing
const sortedArray1 = _.sortBy(array1);
const sortedArray2 = _.sortBy(array2);

// Check for equivalence
const areEqual = _.isEqual(sortedArray1, sortedArray2);
console.log(areEqual); // Output: true
true

Converting to Sets and Comparing

In this approach, Arrays array1 and array2 are transformed into sets, with each inner array being converted into a set of unique elements. The sets are then compared for equality, and the result is logged to the console, which returns true in this case.

Example: The below example shows how to Compare Jagged Arrays using Lodash with Converting to Sets and Comparing.

JavaScript
const _ = require("lodash");

const array1 = [
    ["a", "b"],
    ["b", "c"],
];
const array2 = [
    ["b", "c"],
    ["a", "b"],
];
// Convert to sets before comparing
const set1 = new Set(array1.map((innerArray) => new Set(innerArray)));
const set2 = new Set(array2.map((innerArray) => new Set(innerArray)));
// Check for equivalence
const areEqual = _.isEqual(set1, set2);
console.log(areEqual); // Output: true

Output:

true

Contact Us