Sort an array of objects based on values ​​in objects

I have an array of objects

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

I want to sort it in ascending order value

+4
source share
3 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. Stable JavaScript sorting is not guaranteed.

+3
source

Try the following:

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

+1
source

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/

+1
source

Source: https://habr.com/ru/post/1536533/


All Articles