Tuesday 21 November 2017

javascript sorting array of objects by string property






I am trying to sort an array of object by a property
title. This the code snippet that I am running but it does not
sort anything. The array is displayed as it is. P.S I looked at previous similar
questions. This one for example href="https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript">here
suggests and uses the same method I am
using.



The
javascript:



function sortLibrary()
{
// var library is defined, use it in your code
// use
console.log(library) to output the sorted library data
console.log("inside
sort");
library.sort(function(a,b){return a.title - b.title;});

console.log(library);

}

// tail starts
here
var library = [
{
author: 'Bill Gates',

title: 'The Road Ahead',
libraryID: 1254
},

{

author: 'Steve Jobs',
title: 'Walter
Isaacson',
libraryID: 4264
},
{
author:
'Suzanne Collins',
title: 'Mockingjay: The Final Book of The Hunger
Games',
libraryID: 3245

}
];


sortLibrary();


The
html
code:






charset="UTF-8">





Test Page








Answer




Have you tried like this? It is working as
expected




library.sort(function(a,b)
{return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);}
);


data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">var library =
[
{
author: 'Bill Gates',
title: 'The Road
Ahead',

libraryID: 1254
},
{

author: 'Steve Jobs',
title: 'Walter Isaacson',
libraryID:
4264
},
{
author: 'Suzanne Collins',
title:
'Mockingjay: The Final Book of The Hunger Games',

libraryID:
3245
}
];
console.log('before
sorting...');
console.log(library);
library.sort(function(a,b)
{return (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0);}
);

console.log('after
sorting...');
console.log(library);






No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...