简体   繁体   中英

How to find the highest value for a column nested in JSON?

I want to find the maximum value in a JSON object. This is my data-

(3) [{…}, {…}, {…}]
0: {name: "a", value: 12}
1: {name: "b", value: 28}
2: {name: "c", value: 60}

I'd like to get the maximum value, but they're nested. I could do something like this

arr = {}    
for (x in jsonObj){
  arr.push(x.value)
}    
d3.max(arr)

I was curious if there's a better way of dealing with this situation. My goal is to use d3.max() to find the highest value.

Although the other answers by Hrishi and Nina Scholz are perfectly fine, I would like to mention that the idiomatic way using D3 is to utilize d3.max() . You can pass in an accessor function as the second argument which will be invoked for every member of the array and returns the nested value you are interested in.

 const data = [ {name: "a", value: 12}, {name: "b", value: 28}, {name: "c", value: 60} ]; const maxValue = d3.max(data, d => d.value); // accessor function ---^ console.log(maxValue); // 60 
 <script src="https://d3js.org/d3.v5.js"></script> 

array = [
    { name: "a", value: 12 },
    { name: "b", value: 28 },
    { name: "c", value: 60 },
]

console.log(Math.max.apply(Math, array.map(function (e) { return e.value; })));

You could reduce the array by taking a really small value as start value and get the max of the accumulator and the value.

 var array = [{ name: "a", value: 12 }, { name: "b", value: 28 }, { name: "c", value: 60 }], max = array.reduce((max, { value }) => Math.max(max, value), -Infinity); console.log(max); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM