我正在尝试根据年龄组对数组进行排序,然后是性别。我已经提出了一个解决方案,它可以工作,但我认为代码可以在某个地方改进,但我无法弄清楚如何。以下是示例输入:
// removed
我的代码:
// removed code
我得到的输出是正确的:
male 2,0,0,0,1,0,0,0,0
female 0,0,0,1,3,1,0,0,0
我很确定在速度性能方面有更好的方法来实现这一目标。有任何想法吗?
答案 0 :(得分:1)
您可以使用array#reduce
。
var obj = [[{"age":41,"gender":"male"}],[{"age":10,"gender":"male"}],[{"age":10,"gender":"male"}],[{"age":31,"gender":"female"}],[{"age":58,"gender":"female"}],[{"age":50,"gender":"female"}],[{"age":50,"gender":"female"}],[{"age":50,"gender":"female"}]];
var result = obj.reduce(function(data,a){
++data[a[0]['gender']][a[0]['age'] > 80 ? data[a[0]['gender']].length : Math.ceil(a[0]['age'] / 10 - 1)];
return data;
},{'male' : Array(9).fill(0), 'female' : Array(9).fill(0)});
console.log(result);

如果要对对象进行排序,可以使用自定义排序功能
var obj = [[{"age":41,"gender":"male"}],[{"age":10,"gender":"male"}],[{"age":10,"gender":"male"}],[{"age":31,"gender":"female"}],[{"age":58,"gender":"female"}],[{"age":50,"gender":"female"}],[{"age":50,"gender":"female"}],[{"age":50,"gender":"male"}],[{"age":50,"gender":"female"}]]
var result = obj.sort(function(a,b){
return a[0].age - b[0].age || a[0].gender.localeCompare(b[0].gender);
});
console.log(result);

答案 1 :(得分:0)
您的代码需要4到6毫秒才能对您的样本数据执行。
function ageIndex(elem) {
var age = elem[0].age;
if (age <= 0) return 0;
else if (age > 80) return 8;
else return Math.floor((age - 1) / 10);
}
function gender(elem) { return elem[0].gender }
var ageGroup = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '80+'];
var maleData = new Array(ageGroup.length).fill(0);
var femaleData = new Array(ageGroup.length).fill(0);
l = arr.length;
for (var i = 0; i < l; i++) {
if (gender(arr[i]) == "male") maleData[ageIndex(arr[i])]++;
else femaleData[ageIndex(arr[i])]++;
}
console.log("male " + maleData)
console.log("female " + femaleData)
这个一直给我1毫秒。也许是因为我将数组长度存储在一个变量中,而不是每次都计算它。