Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

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

share|improve this question

marked as duplicate by laggingreflex, Sterling Archer, thefourtheye, karthik, Micha Apr 15 '14 at 5:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 3 down vote accepted

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.

share|improve this answer

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

share|improve this answer

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/

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.