Given a collection of JSON with a structure of id, name and description. Sort them by name.
e.g:
[ { "id": 100, "name": "John", "description":"A real gentleman" }, { "id": 101, "name": "Gary", "description":"A clever person" }, { "id": 102, "name": "Anna", "description":"A charming lass" }, { "id": 103, "name": "Zoltan", "description":"A financial wizard" } ]
should be:
[ { "id": 102, "name": "Anna", "description":"A charming lass" }, { "id": 101, "name": "Gary", "description":"A clever person" }, { "id": 100, "name": "John", "description":"A real gentleman" }, { "id": 103, "name": "Zoltan", "description":"A financial wizard" } ]
function sortByName(collection) {
return collection.sort((a, b) => {
let alpha = a.name.toLowerCase();
let beta = b.name.toLowerCase();
return (alpha < beta) ? -1 : (alpha > beta) ? 1 : 0;
});
}
const chai = require("chai");
const assert = chai.assert;
chai.config.truncateThreshold=0;
describe("Solution", function() {
it("Determine if given collection is sorted by name",
function() {
assert.deepEqual(sortByName([
{ "id": 100, "name": "John", "description":"A real gentleman" },
{ "id": 101, "name": "Gary", "description":"A clever person" },
{ "id": 102, "name": "Anna", "description":"A charming lass" },
{ "id": 103, "name": "Zoltan", "description":"A financial wizard" }
]), [
{ "id": 102, "name": "Anna", "description":"A charming lass" },
{ "id": 101, "name": "Gary", "description":"A clever person" },
{ "id": 100, "name": "John", "description":"A real gentleman" },
{ "id": 103, "name": "Zoltan", "description":"A financial wizard" }
])
});
});