Sorting JavaScript Object by property value

2018-12-31 00:07发布

If I have a JavaScript object such as:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

Is there a way to sort the properties based on value? So that I end up with

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};

28条回答
查无此人
2楼-- · 2018-12-31 00:15

Another way to solve this:-

var res = [{"s1":5},{"s2":3},{"s3":8}].sort(function(obj1,obj2){ 
 var prop1;
 var prop2;
 for(prop in obj1) {
  prop1=prop;
 }
 for(prop in obj2) {
  prop2=prop;
 }
 //the above two for loops will iterate only once because we use it to find the key
 return obj1[prop1]-obj2[prop2];
});

//res will have the result array

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 00:15

Try this. Even your object is not having the property based on which you are trying to sort also will get handled.

Just call it by sending property with object.

var sortObjectByProperty = function(property,object){

    console.time("Sorting");
    var  sortedList      = [];
         emptyProperty   = [];
         tempObject      = [];
         nullProperty    = [];
    $.each(object,function(index,entry){
        if(entry.hasOwnProperty(property)){
            var propertyValue = entry[property];
            if(propertyValue!="" && propertyValue!=null){
              sortedList.push({key:propertyValue.toLowerCase().trim(),value:entry});  
            }else{
                emptyProperty.push(entry);
           }
        }else{
            nullProperty.push(entry);
        }
    });

      sortedList.sort(function(a,b){
           return a.key < b.key ? -1 : 1;
         //return a.key < b.key?-1:1;   // Asc 
         //return a.key < b.key?1:-1;  // Desc
      });


    $.each(sortedList,function(key,entry){
        tempObject[tempObject.length] = entry.value;
     });

    if(emptyProperty.length>0){
        tempObject.concat(emptyProperty);
    }
    if(nullProperty.length>0){
        tempObject.concat(nullProperty);
    }
    console.timeEnd("Sorting");
    return tempObject;
}
查看更多
与君花间醉酒
4楼-- · 2018-12-31 00:16

I made a plugin just for this, it accepts 1 arg which is an unsorted object, and returns an object which has been sorted by prop value. This will work on all 2 dimensional objects such as {"Nick": 28, "Bob": 52}...

var sloppyObj = {
    'C': 78,
    'A': 3,
    'B': 4
};

// Extend object to support sort method
function sortObj(obj) {
    "use strict";

    function Obj2Array(obj) {
        var newObj = [];
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) return;
            var value = [key, obj[key]];
            newObj.push(value);
        }
        return newObj;
    }

    var sortedArray = Obj2Array(obj).sort(function(a, b) {
        if (a[1] < b[1]) return -1;
        if (a[1] > b[1]) return 1;
        return 0;
    });

    function recreateSortedObject(targ) {
        var sortedObj = {};
        for (var i = 0; i < targ.length; i++) {
            sortedObj[targ[i][0]] = targ[i][1];
        }
        return sortedObj;
    }
    return recreateSortedObject(sortedArray);
}

var sortedObj = sortObj(sloppyObj);

alert(JSON.stringify(sortedObj));

Here is a demo of the function working as expected http://codepen.io/nicholasabrams/pen/RWRqve?editors=001

查看更多
查无此人
5楼-- · 2018-12-31 00:16

Just in case, someone is looking for keeping the object (with keys and values), using the code reference by @Markus R and @James Moran comment, just use:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var newO = {};
Object.keys(list).sort(function(a,b){return list[a]-list[b]})
                 .map(key => newO[key] = list[key]);
console.log(newO);  // {bar: 15, me: 75, you: 100, foo: 116}
查看更多
倾城一夜雪
6楼-- · 2018-12-31 00:17

JavaScript objects are unordered by definition (see the ECMAScript Language Specification, section 8.6). The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.

If you need things to be ordered, use an array and the Array.prototype.sort method.

查看更多
低头抚发
7楼-- · 2018-12-31 00:17

We don't want to duplicate the entire data structure, or use an array where we need an associative array.

Here's another way to do the same thing as bonna:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
keysSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]})
console.log(keysSorted);     // bar,me,you,foo

查看更多
登录 后发表回答