54

I would like to create a (non-anonymous) function that sorts an array of objects alphabetically by the key name. I only code straight-out JavaScript so frameworks don't help me in the least.

var people = [
    {'name': 'a75', 'item1': false, 'item2': false},
    {'name': 'z32', 'item1': true,  'item2': false},
    {'name': 'e77', 'item1': false, 'item2': false}
];
13
  • 1
    What do you have so far? Why do you explicitly want a non-anonymous function?
    – pimvdb
    Nov 17, 2011 at 22:12
  • A non-anonymous function sorting(json_object,key_to_sort_by) {}
    – John
    Nov 17, 2011 at 22:14
  • Added the quotes, haven't coded for a few days! Just want to figure out how JSON and JavaScript set the key and then sort. Figure if it's not integer based I could use the sort method perhaps?
    – John
    Nov 17, 2011 at 22:16
  • Anonymous function example: window.onload = function() {/* stuff();*/}
    – John
    Nov 17, 2011 at 22:16
  • 5
    What you list above is not JSON, it is a plain JavaScript object. JSON is the string encoded version of a JavaScript object.
    – Matt
    Nov 17, 2011 at 22:17

12 Answers 12

142

How about this?

var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

people = sort_by_key(people, 'name');

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

7
  • Is it possible to sort by 2 keys? eg. 'last_name', 'first_name'? (similar to mysql's ORDER BY field). Thanks!
    – Josiah
    Jan 2, 2014 at 23:49
  • @DavidBrainer-Banker - I really like the solution in this answer -- what if I wanted to sort by MULTIPLE keys? Is that possible with this solution or better handled another way?
    – tamak
    Dec 2, 2015 at 13:51
  • 1
    It doesn't work with upper/lowercase values. Please update the code with var x = a[key].toLowerCase(); var y = b[key].toLowerCase(); Jan 8, 2019 at 11:12
  • 8
    This algorithm messes up stacksort. Please fix Jul 17, 2019 at 21:02
  • 2
    Hello from StackSort ! Nice answer, did the job.
    – Toodoo
    Oct 4, 2019 at 14:27
32

You can sort an array ([...]) with the .sort function:

var people = [
    {'name': 'a75', 'item1': false, 'item2': false},
    {'name': 'z32', 'item1': true,  'item2': false},
    {'name': 'e77', 'item1': false, 'item2': false},
];

var sorted = people.sort(function IHaveAName(a, b) { // non-anonymous as you ordered...
    return b.name < a.name ?  1 // if b should come earlier, push a to end
         : b.name > a.name ? -1 // if b should come later, push a to begin
         : 0;                   // a and b are equal
});
3
  • Thanks though that is an annoymous function, I'm trying to do function sort_example(object_name,key_to_sort_by) {}
    – John
    Nov 17, 2011 at 22:23
  • 1
    @John: It's a named function expression now :) What you want is not too difficult, have a try.
    – pimvdb
    Nov 17, 2011 at 22:24
  • so after sort what should i console, sorted or people Apr 2, 2018 at 7:08
9

This isn't a JSON question, per se. Its a javascript array question.

Try this:

people.sort(function(a,b){ 
    var x = a.name < b.name? -1:1; 
    return x; 
});
3
  • I'm trying to do function sort_example(object_name,key_to_sort_by) {}
    – John
    Nov 17, 2011 at 22:23
  • 2
    +1 I used this to sort prices and I just inverted the bracket '<' for '>' and I got the prices sorted from lowest to highest. Thank you! Sep 15, 2014 at 20:42
  • 1
    This can blow badly because of comparing same elements returning 1. Depending on the sort function user, anything can happen.
    – maaartinus
    May 11, 2017 at 14:18
5

I modified @Geuis 's answer by using lambda and convert it upper case first:

people.sort((a, b) => a.toLocaleUpperCase() < b.toLocaleUpperCase() ? -1 : 1);
4

My solution for similar sort problem using ECMA 6

var library = [
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, 
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},
        {name: 'Asad', course:'SWE', courseID: 'cs542'},
];

const sorted_by_name = library.sort( (a,b) => a.name > b.name );

for(let k in sorted_by_name){
    console.log(sorted_by_name[k]);
}

2
  • Interesting though subjective to browser share / compatibility. If it will work in IE11 then 2017 compatibility is fair otherwise if it requires IE12 ("Edge") it will have to wait until circa 2020. Looks slightly less verbal...though when I originally posted this I asked for a non-anonymous function I could call.
    – John
    Sep 5, 2017 at 1:08
  • Are you sure this is meant to work according to standards? < on strings returns just true or false on Node v14.17.0, not the desired -1, 0, 1. Jun 17, 2021 at 10:28
2
Array.prototype.sort_by = function(key_func, reverse=false){
    return this.sort( (a, b) => ( key_func(b) - key_func(a) ) * (reverse ? 1 : -1) ) 
}

Then for example if we have

var arr = [ {id: 0, balls: {red: 8,  blue: 10}},
            {id: 2, balls: {red: 6 , blue: 11}},
            {id: 1, balls: {red: 4 , blue: 15}} ]

arr.sort_by(el => el.id, reverse=true)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},
  { id: 1, balls: {red: 4 , blue: 15 }},
  { id: 0, balls: {red: 8 , blue: 10 }} ]
*/

or

arr.sort_by(el => el.balls.red + el.balls.blue)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},    // red + blue= 17
  { id: 0, balls: {red: 8 , blue: 10 }},    // red + blue= 18
  { id: 1, balls: {red: 4 , blue: 15 }} ]   // red + blue= 19
*/
1

var data = [ 1, 2, 5, 3, 1]; data.sort(function(a,b) { return a-b });

With a small compartor and using sort, we can do it

0

This is how simply I sort from previous examples:

if my array is items:

0: {id: 14, auctionID: 76, userID: 1, amount: 39}
1: {id: 1086, auctionID: 76, userID: 1, amount: 55}
2: {id: 1087, auctionID: 76, userID: 1, amount: 55}

I thought simply calling items.sort() would sort it it, but there was two problems: 1. Was sorting them strings 2. Was sorting them first key

This is how I modified the sort function:

for(amount in items){
if(item.hasOwnProperty(amount)){

i.sort((a, b) => a.amount - b.amount);
}
}
0

Sorting alphabetically with lambda function:

arr.sort((a, b) => a.name.localeCompare(b.name));
-1

var library = [
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, 
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},
        {name: 'Asad', course:'SWE', courseID: 'cs542'},
];

const sorted_by_name = library.sort( (a,b) => a.name > b.name );

for(let k in sorted_by_name){
    console.log(sorted_by_name[k]);
}

2
  • 1
    It is always nice to put some explanatory text along with your code, when answering questions. Sep 8, 2017 at 12:03
  • The compare function returns a boolean, it should return a number Nov 6, 2017 at 10:45
-1

var library = [
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, 
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},
        {name: 'Asad', course:'SWE', courseID: 'cs542'},
];

const sorted_by_name = library.sort( (a,b) => a.name > b.name ? 1:-1 );

for(let k in sorted_by_name){
    console.log(sorted_by_name[k]);
}

1
  • 2
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    May 12, 2022 at 10:37
-3
var people = 
[{"name": 'a75',"item1": "false","item2":"false"}, 
{"name": 'z32',"item1": "true","item2":  "false"}, 
{"name": 'e77',"item1": "false","item2": "false"}]; 

function mycomparator(a,b) {   return parseInt(a.name) - parseInt(b.name);  } 
people.sort(mycomparator); 

something along the lines of this maybe (or as we used to say, this should work).

2
  • 2
    parseInt('a75') is NaN so this won't really work I guess.
    – pimvdb
    Nov 17, 2011 at 22:25
  • I don;t think this is appropriate solution when we are dealing with string value, because parseInt on string might give unexpected value, but yaa if you are comparing a string having numeric or decimal value then it will work Aug 11, 2019 at 3:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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