gpt4 book ai didi

javascript - 分组然后过滤

转载 作者:行者123 更新时间:2023-12-01 01:56:59 25 4
gpt4 key购买 nike

我有以下对象。

car = [{
Acc: "X1",
primary: true,
Name: "Park Street",
Date: "2018/01/01"
},{
Acc: "X1",
primary: false,
Name: "Park Street 2",
Date: "2018/03/01"
},{
Acc: "X2",
primary: false,
Name: "Park Street 3",
Date: "2018/01/01"
},{
Acc: "X2",
primary: false,
Name: "Park Street 4",
Date: "2018/05/01"
}];

我必须从每组“Acc”中仅获取一个元素。 Acc:“X1”和 Acc:“X2”各一个元素。查找的逻辑应该是 if Primary: true,然后从组中选择该元素,否则选择具有最新 Date: 值的元素。

我确实知道这个要求可以使用下划线js来实现,但我是新手,无法找出相关的方法。

有人可以帮我吗?

最佳答案

实现此目的的一种方法是,首先按 Acc 进行分组,然后在组内按 primaryDate 降序排序,然后只需选择每组中的第一个即可。

例如。

const car = [{
Acc: "X1",
primary: true,
Name: "Park Street",
Date: "2018/01/01"
},{
Acc: "X1",
primary: false,
Name: "Park Street 2",
Date: "2018/03/01"
},{
Acc: "X2",
primary: false,
Name: "Park Street 3",
Date: "2018/01/01"
},{
Acc: "X2",
primary: false,
Name: "Park Street 4",
Date: "2018/05/01"
}];


//lets group
const grouped = car.reduce((a, v) => {
if (!a[v.Acc]) a[v.Acc] = [];
a[v.Acc].push(v);
return a;
}, {});

//now for each group sort by primary, and then Date
const result = Object.values(grouped).map((g) => {
g.sort((a, b) => b.primary - a.primary || b.Date.localeCompare(a.Date));
return g[0]; //now sorted, pick first.
});

console.log(result);

另一种更有效的方法,可能只是跟踪对象文字中的最佳内容..

例如..

const car = [{
Acc: "X1",
primary: true,
Name: "Park Street",
Date: "2018/01/01"
},{
Acc: "X1",
primary: false,
Name: "Park Street 2",
Date: "2018/03/01"
},{
Acc: "X2",
primary: false,
Name: "Park Street 3",
Date: "2018/01/01"
},{
Acc: "X2",
primary: false,
Name: "Park Street 4",
Date: "2018/05/01"
}];

const best = {};

car.forEach((c) => {
const b = best[c.Acc] = best[c.Acc] || c;
if (b.primary) return;
if (c.Date.localeCompare(best.Date) < 0) best[c.Acc] = c;
});

console.log(Object.values(best));

关于javascript - 分组然后过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50937647/

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