jquery - fastest way to group keys with the same numeric value from a javascript object? -
'lets have object
var obj = { apples: 2, grapes: 1, oranges:2, carrots:2, potatoes: 4 }
how write fast executing function return keys grouped values?
return { "2": ['apples', 'oranges', 'carrots'], "4" : ['potatoes'], "1" : ['grapes'] }
you can use simple for..in
achieve this:
var obj = { apples: 2, grapes: 1, oranges:2, carrots:2, potatoes: 4 }; var result = {}; for(var key in obj) { if(!(obj[key] in result)) result[obj[key]] = []; result[obj[key]].push(key); } console.log(result);
Comments
Post a Comment