-1

How would you find the minimum value in this object in d3?

{Mon: 3.7, Tues: 1.2, Wed: 2.4, Thurs: 9.6....}

  • possible duplicate of [Obtain smallest value from array in Javascript?](http://stackoverflow.com/questions/8934877/obtain-smallest-value-from-array-in-javascript) – Misiur Apr 07 '14 at 08:22
  • This is not an array, it's an object. All you need to do is check every value of the object: http://stackoverflow.com/questions/684672/loop-through-javascript-object – Stilltorik Apr 07 '14 at 08:24

4 Answers4

1

If you just want the value itself, use d3.min and d3.values:

var obj = {Mon: 3.7, Tues: 1.2, Wed: 1.4, Thurs: 9.6};
var min = d3.min(d3.values(obj)); // 1.2

If you want to know the member that contains the min value, use d3.entries and Array.reduce:

min = d3.entries(obj).reduce(function(memo, item){
  return memo.value > item.value ? memo : item;
}); // {key: "Tues", value: 1.2}
bollwyvl
  • 1,231
  • 11
  • 6
0

You could use underscorejs max:

var obj = {Mon: 3.7, Tues: 1.2, Wed: 2.4, Thurs: 9.6};
var max = _.max(obj); // 9.6

and userscorejs min:

var obj = {Mon: 3.7, Tues: 1.2, Wed: 2.4, Thurs: 9.6};
var min = _.min(obj ); // 1.2
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
0

You could make a loop that goes through the object and compares its values. Heres a code:

var obj= {Mon: 3.7, Tues: 1.2, Wed: 2.4, Thurs: 9.6};
var keys = Object.keys(obj);
var leastEl = obj[keys[0]];

for (var i = 0; i < keys.length; i++) {
    if (leastEl > obj[keys[i]]) {
        leastEl = obj[keys[i]];   
    }
}

demo

edit: and yeah - as someone already stated above - your given example doesnt have any array inside, it has an object.

0
        var obj = {Mon: 3.7,Tues: 1.2,Wed: 1.4}
        var min;
        for(var x in obj){

            if(min == undefined || obj[x]<min){
                min=obj[x];
            }

        }
        console.log(min);
smistry
  • 1,127
  • 1
  • 9
  • 9