gpt4 book ai didi

javascript - 使用下划线过滤数组中的唯一和重复对象

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

我有一个对象数组:

data = [{"origin":"SJU","dest":"JFK","rank":48},{"origin":"JFK","dest":"SJU","rank":21},{"origin":"IAD","dest":"LAX","rank":31},{"origin":"LAS","dest":"SJU","rank":21}]

我正在尝试通过“来源”和“目标”提取所有重复项和唯一对象。所以这2个是一样的,忽略rank key

  • {origin:'JFK',dest:'SJU',rank:21}
  • {"origin":"SJU","dest":"JFK","rank":48}

基本上我想要 2 个单独的数组:

duplicates=[{"origin":"SJU","dest":"JFK","rank":48},{"origin":"JFK","dest":"SJU", “等级”:21}]

unique = [{"origin":"IAD","dest":"LAX","rank":31},{"origin":"LAS","dest":"SJU", “等级”:21}]

使用下划线,我能够将类似的东西放在一起。但它似乎效率低下,只返回一个重复数组:

duplicates = _.chain(data).map(function (d) {
var ar = [d.origin, d.dest];
return ar.sort();
}).sortBy(function (d) {
return d
}).groupBy(function (d) {return d}).map(function (d) {
if (d.length > 1) {
return d[0]
}
}).compact().value()
single = _.chain(data).map(function (d) {
var ar = [d.origin, d.dest];
return ar.sort();
}).sortBy(function (d) {
return d
}).groupBy(function (d) {
return d
}).map(function (d) {
if (d.length == 1) {
return d[0]
}
}).compact().value()

我忍不住觉得有一种更简单的方法可以做到这一点。

最佳答案

引入一个临时变量来保存组可能更容易:

var data = [{"origin":"SJU","dest":"JFK","rank":48},{"origin":"JFK","dest":"SJU","rank":21},{"origin":"IAD","dest":"LAX","rank":31},{"origin":"LAS","dest":"SJU","rank":21}]

var groups = _.groupBy(data, function(item) {
return [item.origin, item.dest].sort();
});

然后:

var duplicates = [],
singles = [];

_.each(groups, function(group) {
if (group.length > 1) {
duplicates.push.apply(duplicates, group);
} else {
singles.push(group[0]);
}
});

Demo

关于javascript - 使用下划线过滤数组中的唯一和重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24327912/

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