If I have the Standard Object
var data = [];
data["Name"] = ["Janet", "James", "Jean", "Joe", "John"];
data["Number"] = [25, 22, 37, 19, 40];
Say I want the minimum number value '19'
How can I return and display the Name associated with the minimum number value? What about the Name associated with the maximum value?
Basically, how can I return two elements at once and how can I find out if they are associated with each other?
I've tried indexOf() but methods don't work properly on Standard Objects. I'm fairly new to Javascript.
EDITED: forgot the square brackets on the array...
Use Math.min.apply
to get smallest
value from array
and Array#indexOf
to get index of the smallest
number
var data = {}; //Initialize it as object data["Name"] = ["Janet", "James", "Jean", "Joe", "John"]; data["Number"] = [25, 22, 37, 19, 40]; var min = Math.min.apply(null, data["Number"]); console.log(min); console.log(data["Name"][data["Number"].indexOf(min)]); //-----------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^To get the index of smallest number
The alternative solution using ES6 Array.prototype.find() function:
// search for MAX number
var idx = data["Number"].indexOf(Math.max.apply(null, data["Number"])),
nameWithMax = data["Name"].find((v, i) => i === idx);
console.log(nameWithMax); // "John"
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.