Underscore - Compare two arrays of objects (positions)

瘦欲@ 提交于 2019-12-11 09:57:35

问题


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());


来源:https://stackoverflow.com/questions/24336485/underscore-compare-two-arrays-of-objects-positions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!