Reputation: 8621
I have an array in javascript with this structure:
controllers: Array(2)
0: Object
vram: 4095
1: Object
vram: 1024
This array is generated via si.graphics. There can be more sub-arrays with different values.
I need to somehow return just the index of the controller with the most vram. I've found other stack questions about something similar, but seemingly only with flat arrays, but this array is multi-dimensional.
I haven't tried much to accomplish this because I simply do not know where to start.
How can I get the index of the sub-array with the most vram?
This is not a duplicate because it is focusing on getting the highest value itself, which is pretty trivial and is not what I am/was asking for.
Upvotes: 1
Views: 67
Reputation: 8670
Simply iterate the controllers
Object, and check each vram
value, storing always the highest one, would do the trick
let controllers = [
{"vram":4095}, // index 0
{"vram":1024}, // index 1
{"vram":55555}, // index 2
{"vram":123} // index 3...
];
let max = 0;
for(let i in controllers){
if(controllers[i].vram > controllers[max].vram ) max = i
}
console.log(max); // outputs 2
Upvotes: 1
Reputation: 2024
If you are just trying to get the the highest value then the following function in the code snippet will do what you need:
const myArray = [
{vram: 100},
{vram: 200},
{vram: 150}
]
function getHighestVram(array){
let highestVram = 0;
for (i in array){
if(array[i].vram > highestVram) {
highestVram = array[i].vram;
}
}
return highestVram;
}
const maxVram = getHighestVram(myArray);
console.log(maxVram);
If you want to find the index with the highest vram you can use a similar function. Like this:
const myArray = [
{vram: 100},
{vram: 200},
{vram: 150}
]
function getHighestVram(array){
let highestVram = 0;
let highestVramIndex;
for (i in array){
if(array[i].vram > highestVram) {
highestVram = array[i].vram;
highestVramIndex = i;
}
}
return highestVramIndex;
}
const maxVramIndex = getHighestVram(myArray);
console.log(maxVramIndex);
Upvotes: 1
Reputation: 386560
You could reduce the array by checking the value and with the value of the last max value.
var controllers = [{ vram: 4095 }, { vram: 1024 }],
maxIndex = controllers.reduce(
(r, { vram }, i, a) => !i || vram > a[r].vram ? i : r,
undefined
);
console.log(maxIndex);
Upvotes: 1
Reputation: 5488
Use something like below
var controllers = {
0: {
vram: 4096
},
1: {
vram: 1024
},
2: {
vram: 1024
}
};
var max = -999999,
maxKey = -1;
for(var key in controllers) {
if(controllers[key]['vram'] > max) {
max = controllers[key]['vram'];
maxKey = key;
}
}
console.log(maxKey);
console.log(max);
Upvotes: 1