0
var items = [
    {
        "id": 376,
        "name": "b"
    },
    {
        "id": 253,
        "name": "f"
    },
    {
        "id": 236,
        "name": "c"
    },
    {
        "id": 235,
        "name": "e"
    },
    {
        "id": 165,
        "name": "a"
    },
    {
        "id": 26,
        "name": "d"
    },
    {
        "id": 24,
        "name": "d"
    }
]

How can i sort array by name?

lanzz
  • 42,060
  • 10
  • 89
  • 98

6 Answers6

2

Since you are using strings try

items.sort(function (o1, o2) {
    return o1.name.localeCompare(o2.name)
});
console.log(items)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

There's a good example of sorting on a key here.

The example given in that answer looks like this:

items.sort(function(a, b){
    var keyA = new Date(a.name),
    keyB = new Date(b.name);
    // Compare the 2 dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});
Community
  • 1
  • 1
aquemini
  • 950
  • 2
  • 13
  • 32
  • 2
    So what's the point of doing copy-paste then rather than marking as duplicate? – Alma Do Feb 03 '14 at 08:52
  • 3
    if it were me, i'd prefer the answer to be right under the question i asked. also i changed the name of the key from that question. so relax. – aquemini Feb 03 '14 at 08:54
0

This is an array of objects. You'll need to write your own compare function.

function compare(a,b) {
  if (a.name < b.name)
  {
      return -1;
  }
  if (a.name > b.name)
  {
      return 1;
  }

  return 0;
}

Then sort it like so:

items.sort(compare);
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
0

Here you go:

function byName(a, b){
  var nameA = a.name.toLowerCase();
  var nameB = b.name.toLowerCase(); 
  return ((nameA < nameB) ? -1 : ((nameA > nameB) ? 1 : 0));
}

array.sort(byName);

More about .sort()

Magnus Engdal
  • 5,446
  • 3
  • 31
  • 50
0

you can use this simple code:

myarray.sort(function(a, b){
    var keyA = new Date(a.updated_at),
    keyB = new Date(b.updated_at);
    // Compare dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});
Jess Stone
  • 677
  • 8
  • 21
0

This Could Work

function SortByName(a, b){
  var aName = a.id;
  var bName = b.id; 
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

items.sort(SortByName)