Sort an Array of Objects
Quick demo on how to sort an Array of Objects by key.
HTML
<p>Quick demo on how to sort an Array of Objects.</p>
<p>Unsorted:</p>
<p id="unsorted"></p>
<p>Sorted by name:</p>
<p id="sortedByName"></p>
<p>Sorted by age:</p>
<p id="sortedByAge"></p>
CSS
p {
font: 1em Arial, Helvetica, sans-serif;
}
JavaScript
(function () {
'use strict';
var unsorted = [{
name: 'Peter',
age: 35
}, {
name: 'John',
age: 34
}, {
name: 'Jess',
age: 46
}, {
name: 'Alice',
age: 32
}],
sortedByName = sortByKey(unsorted, 'name'),
sortedByAge = sortByKey(unsorted.slice(0), 'age');
/**
* Get a DOM element by ID
* @param {String} id
* @return {Object}
*/
function $dom(id) {
return document.getElementById(id);
}
/**
* Sort an array of Objects based on key
* @param {Array} array
* @param {String} key
* @returns {Array}
*/
function sortByKey(array, key) {
return array.sort(function (a, b) {
var x = a[key],
y = b[key];
if (typeof x === 'string') {
x = x.toLowerCase();
y = y.toLowerCase();
if (!isNaN(x) && !isNaN(y)) {
x = parseInt(x, 10);
y = parseInt(y, 10);
}
}
return (x < y ? -1 : (x > y ? 1 : 0));
});
}
/**
* Build a HTML String with the people their age
* @param {Array} array
* @return {String}
*/
function getPeople(array) {
for (var i = 0, len = array.length, returnString = ''; i < len; i ++) {
returnString += array[i].name + ', ' + array[i].age + '<br/>';
}
return returnString;
}
// Update the DOM
$dom('unsorted').innerHTML = getPeople(unsorted);
$dom('sortedByName').innerHTML = getPeople(sortedByName);
$dom('sortedByAge').innerHTML = getPeople(sortedByAge);
console.log(getPeople(sortedByName));
})();