I have JavaScript dict object like
[2,1920][2,1080][2,700][3,1200][3,1000][3,800][4,1000][4,900][4,1920]
I need an array of max values, key-wise, e. g.:
[2,1920][3,1200][4,1920]
How can I achieve this?
I have JavaScript dict object like
[2,1920][2,1080][2,700][3,1200][3,1000][3,800][4,1000][4,900][4,1920]
I need an array of max values, key-wise, e. g.:
[2,1920][3,1200][4,1920]
How can I achieve this?
Simply loop over it and compute the maxima. Since you gave only a pseudo notation of your data structure, I can only give you (pythonic) pseudo code:
maxima = new dict()
for each (key, value) in your_object:
if not( key ispartof maxima ) or maxima.get(key) < value:
maxima.set(key, value)
Not the shortest way (2n complex), but it works:
var dataArr = [[2,1920],[2,1080],[2,700],[3,1200],[3,1000],[3,800],[4,1000],[4,900],[4,1920]];
dataArr.sort(function (a,b) {
if (a[0] === b[0]) {
return b[1] - a[1];
}
});
var key = dataArr[0][0];
var currentKey;
var index = 1;
var arrLength = dataArr.length;
for (index; index < arrLength; index++) {
currentKey = dataArr[index][0];
if (key === currentKey) {
delete dataArr[index];
} else {
key = currentKey;
}
}
console.log(dataArr);
I think this is what you want.
var dict, maxes, keys, keyi, key;
// you can represent your data in a dictionary like this
dict = {2: [1920,1080,700], 3: [1200,1000,800], 4: [1000,900,1920]};
// this will get the max values for each key in the dicionary
maxes = {};
keys = Object.keys(dict);
for (keyi = 0; keyi < keys.length; keyi++) {
key = keys[keyi];
maxes[key] = Math.max.apply(Math, dict[key]);
}
In the end, the maxes
will contain:
{2: 1920, 3: 1200, 4: 1920}