Sort an array of objects based on values in the objects

This question already has an answer here:

  • Sort array of objects by string property value in JavaScript 33 answers

  • Since your values are just numbers, you can return their differences from the comparator function

    winners_tie.sort(function(first, second) {
        return first.value - second.value;
    });
    
    console.log(winners_tie);
    

    Output

    [ { name: 'A', value: 111 },
      { name: 'C', value: 222 },
      { name: 'B', value: 333 } ]
    

    Note: JavaScript's sort is not guaranteed to be stable.


    Try this one:

    function compare(a,b) {
      if (a.value < b.value)
         return -1;
      if (a.value > b.value)
        return 1;
      return 0;
    }
    
    winners_tie.sort(compare);
    

    For Demo : Js Fiddle


    For arrays:

    function sort_array(arr,row,direc) {
        var output = [];
        var min = 0;
    
        while(arr.length > 1) {
            min = arr[0];
            arr.forEach(function (entry) {
                if(direc == "ASC") {
                    if(entry[row] < min[row]) {
                        min = entry;
                    }
                } else if(direc == "DESC") {
                    if(entry[row] > min[row]) {
                        min = entry;
                    }
                }
            })
            output.push(min);
            arr.splice(arr.indexOf(min),1);
        }
        output.push(arr[0]);
        return output;
    }
    

    http://jsfiddle.net/c5wRS/1/

    链接地址: http://www.djcxy.com/p/19336.html

    上一篇: 按特定键值排序对象数组

    下一篇: 根据对象中的值对一组对象进行排序