2

I've got an array with following format:

var dataset = [{
    date: '1',
    value: '55'
}, {
    date: '2',
    value: '52'
}, {
    date: '3',
    value: '47'
}];

And I'm getting the maximum value in it by:

var maxValue = Math.max.apply(Math, dataset.map(function(o) {
    return o.value;
}));

It works very well, there's nothing to worry about. But how I can obtain an index of the maxValue?

I've tried indexOf() (which returns me -1 all the time), jQuery inArray() as well as reduce() but none of them work properly.

I guess there's a more cleaner way by iterating all elements to get the index.

Thanks in advance.

1
  • What is the expected result? 0 (55 is the first element) or 1 (55 corresponds to date = 1)? Commented Jul 29, 2015 at 9:16

2 Answers 2

3

As an alternative with Array.forEach

var dataset = [{date:'1',value:'55'},{date:'2',value:'56'},{date:'3',value:'47'}],
    max = -Infinity,
    key;  

dataset.forEach(function (v, k) { 
    if (max < +v.value) { 
        max = +v.value; 
        key = k; 
    }
});

console.log(key);
console.log(dataset[key]);

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, it seems to work! Thank you, it's very helpful!
2

You can use the temp array created by Array.mp() to find the index like

var dataset = [{
  date: '1',
  value: '55'
}, {
  date: '2',
  value: '59'
}, {
  date: '3',
  value: '47'
}];

var tmp = dataset.map(function(o) {
  return o.value;
});
var maxValue = Math.max.apply(Math, tmp);
//find the index using the tmp array, need to convert maxValue to a string since value is of type string
var index = tmp.indexOf(maxValue + '');

snippet.log(maxValue + ' : ' + index)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

5 Comments

Thanks. This is more likely what I was doing, when I'm trying this one - it still returning index -1.
@Bohdan did you use tmp.indexOf(maxValue + ''); or just tmp.indexOf(maxValue);
@Bohdan - Go up with Arun way
I did it. The max value is doing fine and it's correct but index is still -1.
Unfortunately, even though your solution seems to be correct and it works in fiddle, it doesnt work in my case (I tried to recreate my issue but it's alright when testing in fiddle).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.