AKG
AKG

Reputation: 3286

Filter object keys beginning with a certain string

I have an object with these property keys:

instance['banana'];
instance['cl'];
instance['cl2'];
instance['minion'];
instance['cl3'];

I'd like to determine what is the highest number amongst the property keys beginning with 'cl'. So of the filtered 'cl's, I want the 'cl' with the highest number in its key, not in its value. (In this example this would be 'cl3').

So far I'm able to access the instance property keys with Object.keys(instance)(of which I understand works in modern browsers only, but that's okay). Now I need to just filter out all 'cl's and then find out which number is highest.

I guess I should be looking at Math.max for finding out the highest number.

Any nudge in the right direction, por favor? Thanks :)

Upvotes: 0

Views: 260

Answers (1)

elclanrs
elclanrs

Reputation: 94101

var cls = Object.keys(instance).map(function(key){
  return /^cl/.test(key) && +key.replace(/\D+/,'');
});
//^= [false,"",2,false,3] == [0,0,2,0,3]

var maxCl = 'cl'+ Math.max.apply(0, cls); //= "cl3"

Upvotes: 1

Related Questions