Sort an Array of Objects
Quick demo on how to sort an Array of Objects by key.
HTML
<p>Sorted by age:</p>
<p id="sortedByAge"></p>
CSS
Sorted by age (1st sorting option) and Score(2nd sorting option)
want a result like this
Sort with Age and Score
Jess, 46,teacxhing,10
Alice, 0,singing,80
John, 0,document,30
Peter, 0,driving,20
JavaScript
var unsorted = [{
name: 'Peter',
age: 0,
work:'driving',
score : 20
}, {
name: 'John',
age: 0,
work:'document',
score : 30
}, {
name: 'Jess',
age: 46,
work:'teacxhing',
score :10
}, {
name: 'Alice',
age: 0,
work:'singing',
score:80
}],
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 +',' +array[i].work+','+array[i].score+'<br/>';
}
return returnString;
}
// Update the DOM
$dom('sortedByAge').innerHTML = getPeople(sortedByAge);