4

Imagin I have an array

var arr = [ {name: 'peter', age: 50}, {name: 'alice', age: 50}, {name: 'zebra', age: 50}, ];

Now, I wish to sort them on their name. So, that the output is this:

[{name: 'alice', age: 50}, {name: 'peter', age: 50},{name: 'zebra', age: 50}]

The naive solution is to create an array of names and sort them and then loop through this sorted names, find corresponding item in the arr and insert into the new array.

I know this is not the most optimal algorithm and not the cleanest to write.

Can anyone do it more efficiently? Also, note that I am using JavaScript, so I am limited to the libraries and inbuilt functionalities of javaScript which might be easier if we were using Java or some other similar language I guess.

Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63
  • This is almost precisely the same as one of the examples in the Mozilla [Array.prototype.sort() documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Paul Roub Jun 06 '14 at 16:19

1 Answers1

5

You can use the sort function of the Array to implement your sorting by name like:

var arr = [ {name: 'peter', age: 50}, {name: 'alice', age: 50}, {name: 'zebra', age: 50}, ];
arr.sort(function(a,b){ return a.name>b.name; } );

You can read more about it here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
  • This one is a great solution too. I did not know I could do that :P Thanks Dalorzo :) – Cute_Ninja Jun 06 '14 at 16:19
  • 3
    The text sort is a bit better with `return a.localeCompare(b);` because it handles strings that are the same better and handles language issues in sorting. – jfriend00 Jun 06 '14 at 16:21