4

I have an array of objects

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

I wanna sort it in ascending order of value

laggingreflex
  • 32,948
  • 35
  • 141
  • 196

3 Answers3

3

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

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

Bhavesh Kachhadiya
  • 3,902
  • 3
  • 15
  • 20
1

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/

Robin
  • 1,208
  • 8
  • 17