I tried to sort an array of objects. With key and value. I could able to sort with age .but I don't know how to sort with age and score from my object array Any help will be much appreciated
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);