下划线 - 比较对象的两个阵列(位置) [英] Underscore - Compare two arrays of objects (positions)

查看:95
本文介绍了下划线 - 比较对象的两个阵列(位置)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法比较的基础上对它们的元素位置的改变阵列之间的区别是什么?

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

在这种情况下,不清楚为什么'结果'将返回什么。作为有之间没有值的差:[1,2,3]和[1,3,2]。我想在这里实现是一个严格区别,这会看指数为好,从而回到一定的参考对象的新秩序。

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.

推荐答案

如何做这种方式:

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

这篇关于下划线 - 比较对象的两个阵列(位置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆