I am trying to sort an array of object by a propertytitle. 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 examplehere suggests and uses the same method I am using.
The #"inside sort"); library.sort(function(a,b){return a.title - b.title;}); console.log(library);} // tail starts herevar 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:
<html><head> <meta charset="UTF-8"></head><body><h1> Test Page </h1><script src="myscript.js"> </script></body></html>- "Bill Gates" - "Steve Jobs" should be what? Infinity or rather Not a Number ;)?Jonas Wilms– Jonas Wilms2017-08-28 18:01:31 +00:00CommentedAug 28, 2017 at 18:01
5 Answers5
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);} );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);1 Comment
Subtraction is for numeric operations. Usea.title.localeCompare(b.title) instead.
function sortLibrary() { console.log("inside sort"); library.sort(function(a, b) { return a.title.localeCompare(b.title); }); console.log(library);}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();Comments
Use the < or > operator when comparing strings in your compare function.
4 Comments
.sort() callback expects a numeric result, not a boolean, so more than just a drop-in replacement would be needed.you can try this code fromhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
library.sort(function(a, b){var tA = a.title.toUpperCase(); var tB = b.title.toUpperCase(); if (tA < tB) { return -1; } if (tA > tB) { return 1; } return 0;})Comments
Can you try this
FOR DESC
library.sort(function(a,b){return a.title < b.title;});orFOR ASC
library.sort(function(a,b){return a.title > b.title;});Comments
Explore related questions
See similar questions with these tags.



