8 Ways to Compare Arrays in JavaScript
1. Compare two arrays of objects, remove duplicates, merge objects based on properties
We do need to compare two different arrays of objects and want to merge the two objects if they match a specific property value. This can be done using the filter() method. The filter() method creates a new array in which all elements pass the test implemented by the provided function.
Let's create test data:
let array1 = [ { id: "50", value: 10 }, { id: "51", value: 11 } ]; let array2 = [ { id: "53", value: 10 }, { id: "51", value: 11 }, { id: "52", value: 13 } ]; // execute function let res = array2.filter(val => array1.some(({ value }) => (val.value as any) === (value as any)) ); console.log("1", JSON.stringify(res)); //[{"id":"53","value":10},{"id":"51","value":11}]
2. Compare two object arrays, merge and update the values (assuming arrays 3,4 share the same ID)
Sometimes we do have the need to merge two different properties with a new property value. We can use map() to create a new array of objects, and we can use the find() method to match a specific property before updating the new value.
1. The map() method creates a new array filled with the results of calling the provided function on each element in the calling array.
2. The find() method returns the value of the first element in the provided array that satisfies the provided test function. If no value satisfies the test function, undefined is returned.
Let's create test data:
let array3 = [ { id: "50", value: 12 }, { id: "51", value: 15 } ]; let array4 = [ { id: "50", value: 10 }, { id: "51", value: 11 }, { id: "52", value: 13 } ]; // create function let arr = array3.map(id => return { id: id.id, newValue: array4.find(o => o.id === id.id).value + 2 } ); console.log("2", JSON.stringify(arr)); //[{"id":"50","newValue":12},{"id":"51","newValue":13}]
3. Compare arrays of objects and find unique objects
If we want to compare two arrays of objects and check which of them are unique objects, we can use filter() to achieve these functions.
Let's create test data:
const array5 = [ { key: 1, value: 12 }, { key: 2, value: 15 } ]; const array6 = [ { key: 1, value: 12 }, { key: 2, value: 15 }, { key: 3, value: 13 } ]; // create function const ids = array5.map(e => e.key); let filtered = array6.filter(e => ids.includes(e.key)); console.log("3", JSON.stringify(filtered)); //[{"key":"1","value":12},{"key":"2","value":15}]
4. Compare and update properties based on matching values
These functions can be used when we want to compare two arrays of objects and update specific properties based on matching values.
Let's create test data:
const array7 = [ { id: "50", value: 12 }, { id: "51", value: 15 } ]; const array8 = [{ id: "50", value: 12 }]; // create function const idSet = new Set(array8.map(o => o.id)); const res1 = array7.map(o => ({ ...o, value: idSet.has(o.id) ? "0" : o.value })); console.log("4", JSON.stringify(res1)); //[{"id":"50", "value":"0"},{"id":"51","value":15}]
5. Compare two array objects and get the difference
These functions can be used when we want to compare two different arrays of objects and get the difference between them.
Let's create test data:
let a = [ { id: "50", sysNo: 10 }, { id: "51", sysNo: 11 } ]; let b = [ { id: "50", sysNo: 10 }, { id: "51", sysNo: 11 }, { id: "52", sysNo: 13 } ]; // create function let valuesArray1 = a.reduce(function(a, c) { a[c.sysNo] = c.sysNo; return a; }, {}); // valuesArray1: {10: 10, 11: 11} let valuesArray2 = b.reduce(function(a, c) { a[c.sysNo] = c.sysNo; return a; }, {}); // valuesArray2: {10: 10, 11: 11, 13: 13} var result = a .filter(function(c) { return !valuesArray2[c.sysNo]; }) // [] .concat( b.filter(function(c) { return !valuesArray1[c.sysNo]; }) // [{id: "52", sysNo: 13}] ); console.log("5", result); //[{"id":"52","sysNo":13}] //shorthand let ab = b.filter(o => !a.find(o2 => o.id === o2.id)); console.log("6", ab);
6. Merge two arrays of comparison objects and remove duplicates
This method can be used if we have a requirement to compare two arrays of objects and remove duplicates from them and merge the two arrays.
Let's create test data:
let arr1 = [ { id: "1", value: 10 }, { id: "2", value: 11 } ]; let arr2 = [ { id: "1", value: 10 }, { id: "2", value: 11 }, { id: "3", value: 13 } ]; // create function const arr1IDs = new Set(arr1.map(({ id }) => id)); const combined = [...arr1, ...arr2.filter(({ id }) => !arr1IDs.has(id))]; console.log(JSON.stringify(combined)); //[{"id":"1","value":10},{"id":"2","value":11},{"id":"3","value":13}]
7,Lodash
Lodash supports _differenceBy and _differenceWith methods to find the difference between two arrays.
let lodashtest1 = [{ key: "1" }, { key: "2" }]; let lodashtest2 = [{ key: "1" }, { key: "2" }, { key: "3" }]; let lodashresult = _.differenceBy(lodashtest2, lodashtest1, "key"); console.log("7", JSON.stringify(lodashresult)); //[{"key":"3"}] let dif = _.differenceWith(lodashtest2, lodashtest1, _.isEqual); console.log("8",JSON.stringify(dif)); //[{"key":"3"}]
8. Compare objects and find unique values
When we work with nested objects, sometimes it's hard to figure out how we can iterate and compare two nested objects and get some unique objects among them. We can iterate using the Object.keys and Object.values methods.
Let's create test data:
let obj1 = { val1: "test", stream: { prop1: false, prop2: true } }; let obj2 = { val1: "test", stream: { prop1: true, prop2: true } }; interface Data { stream: { [key: string]: boolean }; } // create function function objFilter(objA: Data, objB: Data): Data { let out: Data = { stream: {} }; Object.keys(objA.stream).filter((value, idx) => Object.values(objA.stream)[idx] === Object.values(objB.stream)[idx] ? (out.stream[value] = Object.values(objA.stream)[idx]) : false ); return out; } console.log(JSON.stringify(objFilter(obj1, obj2))); //prop2 //{"stream":{"prop2":true}}