我正在看一些关于人口规模的数据,例如:
const data = [
{ pop: 123, state: "NY" },
{ pop: 102, state: "TX" },
{ pop: 627, state: "FL" },
{ pop: 876, state: "WA" },
{ pop: 211, state: "MI" },
{ pop: 234, state: "CA" }
]我试图在数据集中找到前5个数字,然后在代码的另一部分中使用状态名称作为const的一部分。
我以前用过这样的东西:
const maxPop = d3.max(data, (d, i) => { return d.pop })但我相信这只会是"876“。
我将如何使用它来找到州名-"WA“连接到876上面的数据?那我怎么才能找到其他四个顶级州呢?
发布于 2020-09-13 19:43:45
由于您使用的是箭头函数,所以我假设您可以使用ES6语法,因为d3.max只是一个方便的函数。这里有一个香草的解决方案:
// Just iterate over the array, if the value is larger than the current max,
// store that one instead. Otherwise, keep the current one
const maxByKey = (arr, key) =>
arr.reduce((a, b) => (a[key] > b[key] ? a : b));
const data = [
{ pop: 123, state: "NY" },
{ pop: 102, state: "TX" },
{ pop: 627, state: "FL" },
{ pop: 876, state: "WA" },
{ pop: 211, state: "MI" },
{ pop: 234, state: "CA" }
]
console.log(maxByKey(data, 'pop'));
// logs { "pop": 876, "state": "WA" }
为了获得前五名的州,我只需对名单进行排序,并返回5个最大的州。
let data = [
{ pop: 123, state: "NY" },
{ pop: 102, state: "TX" },
{ pop: 627, state: "FL" },
{ pop: 876, state: "WA" },
{ pop: 211, state: "MI" },
{ pop: 234, state: "CA" },
{ pop: 235, state: "CA" },
{ pop: 236, state: "CA" },
{ pop: 237, state: "CA" },
{ pop: 238, state: "CA" },
{ pop: 238, state: "CA" },
{ pop: 239, state: "CA" }
];
data.sort((a, b) => b.pop - a.pop);
// Data has been sorted, now remove all but the first occurrence of every state
// The logic behind this is that `i` is the index of `d` in the array, and
// indexOf always returns the first match. So if indexOf isn't equal to `i`, then
// `d` is not the first occurrence of that value in the list
const states = data.map((d) => d.state);
data = data.filter((d, i) => states.indexOf(d.state) === i);
console.log(data.slice(0, 5));
/*
[
{
"pop": 876,
"state": "WA"
},
{
"pop": 627,
"state": "FL"
},
{
"pop": 239,
"state": "CA"
},
{
"pop": 211,
"state": "MI"
},
{
"pop": 123,
"state": "NY"
}
]
*/
为了获得前5个州,忽略重复的状态值,我首先尝试将它们“分组”:
const data = [
{ pop: 123, state: "NY" },
{ pop: 102, state: "TX" },
{ pop: 627, state: "FL" },
{ pop: 876, state: "WA" },
{ pop: 211, state: "MI" },
{ pop: 234, state: "CA" }
]
data.sort((a, b) => b.pop - a.pop);
console.log(data.slice(0, 5));
/*
[
{
"pop": 876,
"state": "WA"
},
{
"pop": 627,
"state": "FL"
},
{
"pop": 234,
"state": "CA"
},
{
"pop": 211,
"state": "MI"
},
{
"pop": 123,
"state": "NY"
}
]
*/
发布于 2020-09-13 20:41:13
而不是d3.max,您必须使用d3.greatest,它将返回整个对象:
const data = [{
pop: 123,
state: "NY"
},
{
pop: 102,
state: "TX"
},
{
pop: 627,
state: "FL"
},
{
pop: 876,
state: "WA"
},
{
pop: 211,
state: "MI"
},
{
pop: 234,
state: "CA"
}
];
const max = d3.greatest(data, d => d.pop);
console.log(max)<script src="https://d3js.org/d3.v6.min.js"></script>
https://stackoverflow.com/questions/63874185
复制相似问题