• Register
Welcome to Kodlogs, programming questions and answer website.
0 votes
88 views
I got an array of object that I need to sort by Author using JavaScript. How can I do it?

var user = {

   ID: '3111',

   Author:  "Harfang",

   Title: "Printing Labels",

   Awards: "EC,EEA,CP"

};
by (930 points)  
reopened by

2 Answers

0 votes
 
Best answer

JavaScript Array sort() Method

javascript sort array of objects alphabetically

Example

array sorting:

var animals= ["Owl", "Tiger", "Bird", "Cow"];

animals.sort();

Definition of sort():

This method is used sort array in ascending or descending order.

The sort order is always in ascending order, if string is alphabetical it would sort in

alphabetical order .

This works well for strings as above example like 

animals= ["Owl", "Tiger", "Bird", "Cow"];

if numbers are placed inside as string than 2 might be at top than 10.

So this is incorrect in case of numbers giving false result, the solution for this is to use

"compare function" .

Browser Supported by this method:

The sort array method is supported by following browsers:

Chrome, IE, Firefox, Safari, Opera

Method Syntax 

array.sort(compareFunction)

Parameter Values

Parameter   Description

compareFunction   Optional. 

Some Examples of Sort

Ascending order Sort of numbers:

var nos = [50, 200, 2, 6, 26, 11];

nos.sort(function(a, b){return a-b});

Example

descending order Sort of numbers:

var nos = [50, 200, 2, 6, 26, 11];

nos.sort(function(a, b){return b-a});

Example

Alphabetically Sort an array , and then reverse in descending order of the sorted items :

var animals= ["Owl", "Tiger", "Bird", "Cow"];

animals.sort();

animals.reverse();

by (930 points)  
selected by
0 votes
Another example to sort array of objects alphabetically is following code:

var Employee= {

 

   email:  "eva@some.com",

   firstname: "Eva",

   Empid: 1001,

   lastname: "Smith",

   Address: "Sydney"

};

users.sort(function(a, b){

    if(a.firstname < b.firstname) { return -1; }

    if(a.firstname > b.firstname) { return 1; }

    return 0;

})
by (930 points)  
...