1

Possible Duplicate:
How to sort an array of objects?

Given the array of record of students below - how would you sort them in ascending order using Javascript according to age?

students = [{
name: "timothy",
age: "9"},
{
name: "claire",
age: "12"},
{
name: "michael",
age: "20"}]
Community
  • 1
  • 1
jasonscott
  • 87
  • 1
  • 2
  • 4
  • Ascending by what property? Why are the ages strings and not numbers? – Matt Ball Nov 05 '11 at 17:57
  • Define the term of what you're sorting on first, because you can sort by age or name in your example. Age is easy by implementing a number of sort algorithms using integers. For name, you can convert to and ASCII representation and then again sort on the integer value. Check out quick sort on Wikipedia. – OnResolve Nov 05 '11 at 18:00
  • You can find some useful answers to this topic here: **[Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/a/26759350/2247494)** – jherax Nov 05 '14 at 16:05

5 Answers5

2

To sort in ascending order by age, use Array.sort with a custom comparator function:

students.sort(function (a, b)
{
    return a.age - b.age;
});

// students will be 
[{name: "timothy", age: "9"},
 {name: "claire", age: "12"},
 {name: "michael", age: "20"}]
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Should the function perform a parseInt before performing the subtraction? I would imagine if it's done based on the string representation it might return goofy results. – Joel Etherton Nov 05 '11 at 18:03
  • @Joel `parseInt(age, 10)` would certainly work but is not strictly necessary. Subtraction coerces the operands to numbers. – Matt Ball Nov 05 '11 at 18:47
  • 1
    That would return NaN if one of the values cant be transformed into number. – Ivan Castellanos Nov 05 '11 at 19:48
  • @Ivan true, but there was nothing in the question to suggest that the ages might be non-numeric strings. – Matt Ball Nov 05 '11 at 19:56
0

By age:

students = students.sort(function(a, b) {
  return parseFloat(a.age) - parseFloat(b.age);
});
Svante Svenson
  • 12,315
  • 4
  • 41
  • 45
  • You don't need the `parseFloat` (subtraction will coerce to number) and you don't need the assignment (`Array.sort` is in-place). – Matt Ball Nov 05 '11 at 18:02
0
student.sort(function(a,b){

 if (a.name > b.name)
     return -1;
 return 1;

});
sathis
  • 547
  • 1
  • 3
  • 21
0

Read over this example:

var marks = new Array(10,12,11,20,2);
        for(var i=0;i<marks .length;i++) //Hold the first element
    {
        for(var j=i+1;j<marks.length;j++) //Hold the next element from the first element
        {
            if(Number(marks[i]) > Number(marks[j])) //comparing first and next element
            {
                tempValue = marks[j];   
                marks[j] = marks[i];
                marks[i] = tempValue;
            }
        }
    }
        document.write(marks);
methuselah
  • 12,766
  • 47
  • 165
  • 315
  • 2
    That is a **terrible** sort implementation. – Matt Ball Nov 05 '11 at 18:03
  • I've tried it and it doesn't work? jsfiddle.net/EH8Pm/2/ – jasonscott Nov 05 '11 at 18:17
  • @jason: In your jfiddle example you only swap the ages, instead of the whole array elements. Also, you output `marks` and not `students`. – Paŭlo Ebermann Nov 05 '11 at 18:53
  • @jason: actually, not even that: you are accessing `students.age[i]` instead of `students[i].age`. Have a look at http://jsfiddle.net/EH8Pm/3/ for a working version (though as Matt says, it is not a good algorithm). – Paŭlo Ebermann Nov 05 '11 at 19:05
  • You can find some useful answers to this topic here: **[Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/a/26759350/2247494)** – jherax Nov 05 '14 at 16:06
0
students.sort(function(a,b){
      if (+a.age > +b.age) return 1;
      return -1;
});
// Now the object is ordered by age (min to max)

In case you are wondering, +a.age is the same as Number(a.age)

Ivan Castellanos
  • 8,041
  • 1
  • 47
  • 42
  • What happens if two people have the same age? – Paŭlo Ebermann Nov 05 '11 at 19:06
  • They get together in an position based on their previous position in the array (kind of random). If you want to order them alphabetically when ages are equal you can write this at the beggining `if (+a.age == +b.age) return [a.name,b.name].sort()[0] == a.name ? -1 : 1;` – Ivan Castellanos Nov 05 '11 at 19:42