john
john

Reputation: 17

JS checking object/array for ALL highest values

I know there is Math.max(), reduce(), and even for loop:

var array = [1 , 2 , 3 , 6 , 12 , 13 , 17 , 3];
var biggest = 0;

for (var i = 0; i < array.length; i++)
{
  if(biggest < array[i])
  {
    biggest = array[i];
  }
}
console.log(biggest);

But I need to get EVERY highest element from the object/array. For example I have few measurements:

var object = {m1 : 100 , m2 : 200, m3: 150, m4 : 200, m5 : 100};

So I need to get info from this object that m2 and m4 has the highest values and the value is 200.

The idea is I copy the object (original must be saved for further inspections), get the highest value - save it, remove it from object. I try to find all the rest key:value pairs that has the highest score, by removing every from the object till the object has no more value of 200 (in this example).

Is this a good approach? Maybe I can do something better, or maybe there are some build in JS features that are fastest with better synthetic?

Upvotes: 0

Views: 71

Answers (2)

DecPK
DecPK

Reputation: 25408

To get the highest and the objects whose value is highest, you can match it with the value. If it is greater then you can replace the value.

You also need to maintain the dictionary i.e. dict that contains the objects.

When inserting the value in the dict be sure to first check if the key is already present in dict or not. If it exist then just push the value else create a new array with the value.

var object = { m1: 100, m2: 200, m3: 150, m4: 200, m5: 100 };
let highest = Number.MIN_VALUE;
const dict = {};

Object.entries(object).forEach(([key, value]) => {
  // Replace the stored highest with the value if it is highest
  if (value > highest) highest = value;
  
  // Push the key if the value is already exist in dict
  if (dict[value]) dict[value].push(key);
  else dict[value] = [key];  // else create a new array with the key
});

console.log(highest);
console.log(dict[highest]);

Upvotes: 2

Iziminza
Iziminza

Reputation: 389

I would modify the code like this:

var object = { m1: 100, m2: 200, m3: 150, m4: 200, m5: 100 };
// start with MIN_VALUE so the first entry is accepted as highest
let highest = Number.MIN_VALUE;
// empty result object to start with
let best = {};

// call this function for each key-value-pair
Object.entries(object).forEach(([key, value]) => {
  // if the value is higher than the current maximum,
  if (value > highest) {
      // save the value and create a new, empty result object
      highest = value;
      best = {};
  }
  // only add the key-value-pair to result object if the value
  // equals the current maximum
  if (highest == value) best[key] = value;
});

console.log(highest);
console.log(best);

Upvotes: 1

Related Questions