gpt4 book ai didi

javascript - 下划线 - 比较两个对象数组(位置)

转载 作者:行者123 更新时间:2023-11-30 17:25:39 25 4
gpt4 key购买 nike

有没有办法根据元素位置的变化来比较数组之间的差异?

我有一个原始对象数组,其中一个元素的值发生了变化,这个变化被映射到一个新数组中:

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

在这种情况下,很明显为什么 'result' 不会返回任何内容。因为 [1, 2, 3] 和 [1, 3, 2] 之间的值没有差异。我在这里试图实现的是一个“严格差异”,它也会查看索引,从而返回对对象新顺序的一些引用。

最佳答案

这样做怎么样:

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

关于javascript - 下划线 - 比较两个对象数组(位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com