0

I want to loop through this object and return the keys with the highest property values into an array.

Object {clear-spring: 3, deep-autumn: 2, warm-spring: 1, light-summer: 2, light-spring: 2, clear-summer: 3}

In this case, I want an array like this:

["clear-summer", "clear-spring"]

Is there an efficient way to do this with jQuery or pure javascript?

4 Answers 4

2

You simply need to iterate over your item once, keeping track of what ever the largest set is that you've found so far.

var a = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var max = {
  val: Number.NEGATIVE_INFINITY,
  keys: []
}
for (var prop in a) {
  if (a.hasOwnProperty(prop)) {
    var n = a[prop];
    if (n >= max.val) {
      if (n > max.val) {
        max.keys = [];
      }
      max.val = n;
      max.keys.push(prop);
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good solution to avoid nested or duplicate loops
You can use -Infinity instead of Number.NEGATIVE_INFINITY.
@Oriol Thank you for your comment, I'm well aware of it, but I think the latter is clearer.
0

You may use for.. in to loop through the object

 var object = {clear-spring: 3, deep-autumn: 2, warm-spring: 1, light-summer: 2, light-spring: 2, clear-summer: 3};

 // Iterates over the oject
 for (var key in object) {
     if(object.hasOwnProperty(key)) {
         // Key === 'clear-spring' (sample)
         // object[key] === 3 (sample)
         // do whatever you want
     }
 }

Comments

0
var o = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};

var max = 0, result = [];

// find max:
for(var k in o) { if (o[k] > max) max = o[k] }

// find keys matching the max:
for(var k in o) { if (o[k] === max) result.push(k) }

// log result
console.log(result);

Comments

0

Not sure if most efficient, but first find the max value, then go back and pull out all the ones that match max value.

var obj = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};

var ary = [];
var max = Number.NEGATIVE_INFINITY;

for (var prop in obj) {
    if (obj[prop] > max) {
        max = obj[prop];
    }
}

for (var prop in obj) {
    if (obj[prop] === max) {
        ary.push(prop);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.