Underscore - Compare two arrays of objects (positi

2019-08-12 08:18发布

问题:

Is there a way to compare differences between arrays based on changes on their elements positions?

I have an original array of objects which undergoes a change on one of it's element's values, this change is mapped into a new array:

   origElements = [{id: 1, value: 50}, 
                   {id: 2, value: 60}, 
                   {id: 3, value: 70}]

changedElements = [{id: 1, value: 50},
                   {id: 3, value: 60}, 
                   {id: 2, value: 120}]


var diff = _.difference(_.pluck(origElements, "id"), _.pluck(changedElements, "id"));
var result = _.filter(origElements, function(obj) { return diff.indexOf(obj.id) >= 0; });

In this case it is clear why 'result' would return nothing. As there's no difference of values between: [1, 2, 3] and [1, 3, 2]. What I'm trying to achieve here is a 'strict difference' which would look at index as well, thus returning some reference to the new order of the objects.

回答1:

How about doing it this way:

var origElements = [{
    id: 1,
    value: 50
}, {
    id: 2,
    value: 60
}, {
    id: 3,
    value: 70
}];

var changedElements = [{
    id: 1,
    value: 50
}, {
    id: 3,
    value: 60
}, {
    id: 2,
    value: 120
}];

var origElementsIds = _.pluck(origElements, "id");
var changedElementsIds = _.pluck(changedElements, "id");
console.log("Are array element positions same ?", 
    origElementsIds.join() === changedElementsIds.join());