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?

1
  • This is not a multidimensional array. It's an array of objects. Commented Feb 3, 2014 at 8:53

6 Answers 6

2

Since you are using strings try

items.sort(function (o1, o2) {
    return o1.name.localeCompare(o2.name)
});
console.log(items)
Sign up to request clarification or add additional context in comments.

Comments

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;
});

2 Comments

So what's the point of doing copy-paste then rather than marking as duplicate?
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.
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);

Comments

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()

Comments

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;
});

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.