Comparing Arrays of Objects in JavaScript

Comparing Arrays of Objects in JavaScript

EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.

To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.

Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.


EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).

Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:

function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}

The assumption is that both objects have the same exact list of properties.

Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)

Compare two arrays of objects, and remove if object value is equal

How about using filter and some? You can extend the filter condition on select properties using &&.

const originalArray = [
{ id: 1, name: 'darnell' },
{ id: 2, name: 'funboi' },
{ id: 3, name: 'jackson5' },
{ id: 4, name: 'zelensky' },
];
const itemsToBeRemoved = [
{ id: 2, name: 'funboi', extraProperty: 'something' },
{ id: 4, name: 'zelensky', extraProperty: 'somethingelse' },
];
console.log(
originalArray.filter(item => !itemsToBeRemoved.some(itemToBeRemoved => itemToBeRemoved.id === item.id))
)

How to get the difference between two arrays of objects in JavaScript

Using only native JS, something like this will work:

const a = [{ value:"0", display:"Jamsheer" }, { value:"1", display:"Muhammed" }, { value:"2", display:"Ravi" }, { value:"3", display:"Ajmal" }, { value:"4", display:"Ryan" }];
const b = [{ value:"0", display:"Jamsheer", $$hashKey:"008" }, { value:"1", display:"Muhammed", $$hashKey:"009" }, { value:"2", display:"Ravi", $$hashKey:"00A" }, { value:"3", display:"Ajmal", $$hashKey:"00B" }];

// A comparer used to determine if two entries are equal.
const isSameUser = (a, b) => a.value === b.value && a.display === b.display;

// Get items that only occur in the left array,
// using the compareFunction to determine equality.
const onlyInLeft = (left, right, compareFunction) =>
left.filter(leftValue =>
!right.some(rightValue =>
compareFunction(leftValue, rightValue)));

const onlyInA = onlyInLeft(a, b, isSameUser);
const onlyInB = onlyInLeft(b, a, isSameUser);

const result = [...onlyInA, ...onlyInB];

console.log(result);

How can I compare two arrays of objects and update value when properties match?

I'd suggest making a lookup table (totalByMonth) then you can just loop over the state and update each one by looking up the total in totalByMonth.

const state = [
{total: 0, month_name: "Jan"},
{total: 0, month_name: "Feb"},
{total: 0, month_name: "Mar"},
{total: 0, month_name: "Apr"}
];

const fetched = [
{total: 4, month_name: "Mar"},
{total: 1, month_name: "Apr"}
];

//build totalByMonth object
const totalByMonth = {};
for (let f of fetched) {
totalByMonth[f.month_name] = f.total;
}

//update state
for (let s of state) {
const total = totalByMonth[s.month_name];
if (total) s.total = total;
}

console.log(state);

JavaScript: Comparing arrays of objects with nested array of object

If you like to get only common identifier pairs from both, you could collect the identifier and map the filterd array of arrayB.

This approach takes only one loop for every array.

const
arrayA = [[{ value: "#0767b9", id: 162, productId: 1 }, { value: "#f4b7d4", id: 164, productId: 1 }], [{ value: "#44acd8", id: 102, productId: 2 }], [{ value: "#609923", id: 106, productId: 3 }, { value: "#ee3b70", id: 107, productId: 3 }]],
arrayB = [{ id: 1, optionValue: [{ value: "#002e63", id: 161, productId: 1 }, { value: "#0767b9", id: 162, productId: 1 }, { value: "#010b1d", id: 163, productId: 1 }, { value: "#f4b7d4", id: 164, productId: 1 }] }, { id: 2, optionValue: [{ value: "#EC7063", id: 93, productId: 2 }, { value: "#bf0000", id: 94, productId: 2 }, { value: "#44acd8", id: 102, productId: 2 }, { value: "#ffdbdb", id: 103, productId: 2 }] }, { id: 3, optionValue: [{ value: "#d861bd", id: 105, productId: 3 }, { value: "#609923", id: 106, productId: 3 }, { value: "#ee3b70", id: 107, productId: 3 }] }, { id: 4, optionValue: [{ value: "#44acd8", id: 165, productId: 4 }] }],
identifiers = arrayA.reduce((r, a) => {
a.forEach(({ id, productId }) => (r[productId] = r[productId] || {})[id] = true);
return r;
}, {}),
result = arrayB.map(o => identifiers[o.id]
? { ...o, optionValue: o.optionValue.filter(({ id, productId }) => identifiers[productId][id]) }
: o
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

Just using the Array iteration methods built into JS is fine for this:

var result1 = [    {id:1, name:'Sandra', type:'user', username:'sandra'},    {id:2, name:'John', type:'admin', username:'johnny2'},    {id:3, name:'Peter', type:'user', username:'pete'},    {id:4, name:'Bobby', type:'user', username:'be_bob'}];
var result2 = [ {id:2, name:'John', email:'johnny@example.com'}, {id:4, name:'Bobby', email:'bobby@example.com'}];
var props = ['id', 'name'];
var result = result1.filter(function(o1){ // filter out (!) items in result2 return !result2.some(function(o2){ return o1.id === o2.id; // assumes unique id });}).map(function(o){ // use reduce to make objects with only the required properties // and map to apply this to the filtered array as a whole return props.reduce(function(newo, name){ newo[name] = o[name]; return newo; }, {});});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>';


Related Topics



Leave a reply



Submit