简体   繁体   中英

Sort all key elements by the same value in javascript

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.

This question is a bit unorthodox, but not sure why it was downvoted. Anyway, you can do something like this:

https://jsfiddle.net/wfyndq7x/

var obj = { '290': 'Cat1', '293': 'Cat2', '295': 'Cat1' };

var sortByCat = {}
for (var num in obj) {
    if (obj.hasOwnProperty(num)) {
        if (sortByCat[obj[num]] == null)
            sortByCat[obj[num]] = num;
        else
            sortByCat[obj[num]] += ', ' + num;
    }
}

var catString = ''
for (var catData in sortByCat) {
    if (sortByCat.hasOwnProperty(catData)) {
        catString += catData + ': ' + sortByCat[catData] + ';  ';
    }
}

Basically convert it to a hash with the key as the cat and append the numbers as the value. Then convert to a string so you can print it.

something like this:

var map = {};
var obj = { "290" : "Cat1",  "293" : "Cat2",  "295" : "Cat1" };

for (var i in obj)
{
    var val = obj[i];

    if (!map[val]) map[val] = [];

    map[val].push(i);
}

console.log(map);

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; 

Here is a function that returns grouped Data into another Object.

See it in http://jspin.com/fubeqeweqa

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

function groupByValue(_objectName) {
  var sorted = {};
  for (var obj in _objectName) {

    sorted[_objectName[obj]] = sorted[_objectName[obj]] || [];
    sorted[_objectName[obj]].push(obj);

  }

  return sorted;
}
//{"Cat1":["290","295"],"Cat2":["293"]}
var objectName = { "290" : "Cat1",  "293" : "Cat2",  "295" : "Cat1" };

// build a map where key is category name and value are its associated numbers
var categories = {};
for (var num in objectName) {
     var name = objectName[num];
     if (!categories.hasOwnProperty(name)) {
         categories[name] = [];
     }
     categories[name].push(num);
}
// create formatted string
var sortByCat = '';
for (var name in categories) {
    sortByCat += name + ': ' + categories[name].join(', ') + '; ';
}

console.log(sortByCat);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM