我试图对一组对象进行排序。有关键和价值。我能够按年龄排序。但我不知道如何根据年龄和我的对象数组得分 任何帮助将不胜感激
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);
答案 0 :(得分:0)
我确定您的数据不正确。 json对象正在使用属性,例如:{property_name1:property_value1,property_name2:property_value2} 由于您的数据没有属性名称,我认为您的意思是它的数组数组:
data = [[&#39; workername1&#39;,1,2,32],[&#39; workername2&#39;,40,20,40],[&#39; workername3&#39;, 10,50,10]];
你可以使用array sort来做到这一点,例如:
data.sort(函数(更小,更大){返回更大[3] - 更小[3]});
答案 1 :(得分:0)
您可以使用array#sort
首先对age
进行排序,并使用age
{/ 1}}对score
b.age - a.age || b.score - a.score
进行排序
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 }];
unsorted.sort((a,b) => b.age - a.age || b.score - a.score);
console.log(unsorted);