Ad

Sort All Key Elements By The Same Value In Javascript

- 1 answer

I have an object like this:

var objectName = { "290" : "Cat1",  "293" : "Cat2",  "295" : "Cat1" }

How can I sort an output of elements that have the same value?
I would need something like this:

var sortByCat = 'Cat1: 290, 295; Cat2: 293';

Javascript or jQuery would work just fine.

Ad

Answer

This should do it:

var obj = {
  "290": "Cat1",
  "293": "Cat2",
  "295": "Cat1",
  "291": "Cat1",
  "292": "Cat2",
  "297": "Cat3"
}

var res = JSON.stringify(Object.keys(obj).reduce(function(res, key) {
  if (res[obj[key]]) res[obj[key]].push(key)
  else res[obj[key]] = [key];
  return res;
}, {})).replace(/([,:])/g, "$1 ").replace(/],/g, "]; ").replace(/[{}\[\]"]/g, "");

document.body.innerHTML = res;

Ad
source: stackoverflow.com
Ad