将Javascript数组简化为映射并删除重复的值 [英] Reducing Javascript array into a map and removing duplicate values
问题描述
我敢肯定有一个干净的方法可以做到这一点,但是我不知道该怎么做.我想拔出一列,以便只返回值的第一次出现,但我想保留它附带的键.
I am sure there is a clean way to do this, but I have no idea how to do it. I want to pluck a column out such that I am only returning the first occurrence of a value, but I want to keep the key that went with it.
我有一个要减少的数据集.我想拔出悬崖".
I have a dataset that I want reduced. I want to pluck out the 'precip'.
说我有这个:
[
"2019-01-01" => {"temp" : "cold", "season" : "winter", "precip" : "snow"},
"2019-02-01" => {"temp" : "cold", "season" : "winter", "precip" : "none"},
"2019-03-01" => {"temp" : "mild", "season" : "spring", "precip" : "rain"},
"2019-04-01" => {"temp" : "mild", "season" : "spring", "precip" : "none"},
"2019-05-01" => {"temp" : "warm", "season" : "spring", "precip" : "rain"},
"2019-06-01" => {"temp" : "warm", "season" : "summer", "precip" : "hail"},
"2019-07-01" => {"temp" : "hot", "season" : "summer", "precip" : "none"}
]
我想以此结尾:
[
"2019-01-01" => "snow",
"2019-02-01" => "none",
"2019-03-01" => "rain",
"2019-06-01" => "hail"
]
我认为Array.map与此有关,但是我不知道如何返回键/值对,而不仅仅是返回一个值(即map(function(d) { return d.precip })
)
I would think that Array.map has something to do with this, but I don't know how to return the key/value pair instead of just a value (i.e. map(function(d) { return d.precip })
)
实现此目的的流畅方法是什么?
What is the smooth way to do this?
谢谢.
推荐答案
您可以创建 Map
,并仅获取具有相同键的第一项.
You could create a Map
and take only the first item with the same key.
function getFirstPrecip(data) {
return Object.assign({}, ...Array.from(
data.reduce((m, o) => {
var [[k, { precip }]] = Object.entries(o);
return m.has(precip) ? m : m.set(precip, k);
}, new Map),
([k, v]) => ({ [v]: k })
));
}
var data = [{ "2019-01-01": { temp: "cold", season: "winter", precip: "snow" } }, { "2019-02-01": { temp: "cold", season: "winter", precip: "none" } }, { "2019-03-01": { temp: "mild", season: "spring", precip: "rain" } }, { "2019-04-01": { temp: "mild", season: "spring", precip: "none" } }, { "2019-05-01": { temp: "warm", season: "spring", precip: "rain" } }, { "2019-06-01": { temp: "warm", season: "summer", precip: "hail" } }, { "2019-07-01": { temp: "hot", season: "summer", precip: "none" } }];
console.log(getFirstPrecip(data));
这篇关于将Javascript数组简化为映射并删除重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!