我有一个对象数组,我想获得最大created_on
值。
我试试这段代码:
receipt_details
created_on
但结果是receipt_details
而非created_on
。
我不必使用d3功能,即使纯粹的javascript也没问题。
答案 0 :(得分:3)
您的'NaN'
是字符串,而不是实际的NaN
,但无论如何,您可以在reduce
测试时Math.max
prevalence
:
var ex=[{"name":"a","prevalence":"NaN"},{"name":"a","prevalence":"5"},{"name":"b","prevalence":"0"},{"name":"a","prevalence":"NaN"},{"name":"c","prevalence":"100"},{"name":"c","prevalence":"20"},{"name":"a","prevalence":"3"}];
const max = Math.max(...ex.reduce(
(accum, { prevalence }) =>
isNaN(prevalence) ? accum : [...accum, prevalence],
[])
);
console.log(max);

答案 1 :(得分:2)
实际上"5"
大于"100"
,因为它们被比作字符串。您需要确保将它们作为数字进行比较:
return +d.prevalence;
或者您采取稍微宽松的方法:
const maxPrevalence = Math.max(...ex.map(d => +d.prevalence).filter(p => !isNaN(p)));
答案 2 :(得分:2)
您可以在映射的普遍性值上使用Math.max():
adb devices

答案 3 :(得分:1)
您可以使用Array.reduce
& parseInt
为了迭代数组,并搜索最大值;
parseInt
的使用是必需的,因为普遍性是一个字符串。
const ex = [{
"name": "a",
"prevalence": "NaN"
},
{
"name": "a",
"prevalence": "5"
},
{
"name": "b",
"prevalence": "0"
},
{
"name": "a",
"prevalence": "NaN"
},
{
"name": "c",
"prevalence": "100"
},
{
"name": "c",
"prevalence": "20"
},
{
"name": "a",
"prevalence": "3"
}
];
const result = ex.reduce((max, current) => {
const prevalence = parseInt(current.prevalence) || 0;
return max.prevalence > prevalence ? max : current;
}, {
prevalence: '0'
});
console.log(result);

答案 4 :(得分:1)
使用d3.js,此代码有效。
Number("100")
为100
,Number('NaN')
为NaN
。
// max of selected vaccine
var ex = [{"name": "a", "prevalence": "NaN"}, {"name": "a", "prevalence": "5"}, {"name": "b", "prevalence": "0"}, {"name": "a", "prevalence": "NaN"}, {"name": "c", "prevalence": "100"}, {"name": "c", "prevalence": "20"}, {"name": "a", "prevalence": "3"}];
var maxPrevalence = d3.max(ex, function(d) { return Number(d.prevalence) });
console.log('\nmaxPrevalence:', maxPrevalence);
<script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>