56

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? Commented Nov 17, 2011 at 22:12
  • A non-anonymous function sorting(json_object,key_to_sort_by) {} Commented 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? Commented Nov 17, 2011 at 22:16
  • Anonymous function example: window.onload = function() {/* stuff();*/} Commented 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. Commented Nov 17, 2011 at 22:17

13 Answers 13

144

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/

Sign up to request clarification or add additional context in comments.

7 Comments

Is it possible to sort by 2 keys? eg. 'last_name', 'first_name'? (similar to mysql's ORDER BY field). Thanks!
@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?
It doesn't work with upper/lowercase values. Please update the code with var x = a[key].toLowerCase(); var y = b[key].toLowerCase();
This algorithm messes up stacksort. Please fix
Hello from StackSort ! Nice answer, did the job.
|
33

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 Comments

Thanks though that is an annoymous function, I'm trying to do function sort_example(object_name,key_to_sort_by) {}
@John: It's a named function expression now :) What you want is not too difficult, have a try.
so after sort what should i console, sorted or people
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 Comments

I'm trying to do function sort_example(object_name,key_to_sort_by) {}
+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!
This can blow badly because of comparing same elements returning 1. Depending on the sort function user, anything can happen.
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);

Comments

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 Comments

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.
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.
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
*/

Comments

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

Comments

1

Sorting alphabetically with lambda function:

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

Comments

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

Comments

0

In case if the array is:

    [
      {price:"10"},
      {price:"110"},
      {price:"22"},
    ]

then : (editing John's solution)

    export const sortArrByKey = (array: any[], key: string) => {
      return array.sort(function (a, b) {
        var x = Number(+a[key]) || a[key];
        var y = Number(+b[key]) || b[key];
        return x < y ? -1 : x > y ? 1 : 0;
      });
    };

Comments

-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 Comments

It is always nice to put some explanatory text along with your code, when answering questions.
The compare function returns a boolean, it should return a number
-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 Comment

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.
-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 Comments

parseInt('a75') is NaN so this won't really work I guess.
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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.