Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

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'.

Say I have this:

[
  "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"}
]

I would like to end up with this:

[
  "2019-01-01" => "snow",
  "2019-02-01" => "none",
  "2019-03-01" => "rain",
  "2019-06-01" => "hail"
]

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?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...