第一次海报,长期读者。我在对一组对象进行排序时遇到问题,这是家庭作业,所以我不是要求有人为我编写代码,只是为我指出正确的方向或向我展示我的视线。对象是在传入数组和键时编写一个函数对对象数组进行排序,即:
([{a:2},{b:2},{a:1},{a:3},{b:3},{b:1}], “a”)
应该返回
[{a:1},{a:2},{a:3},{b:1},{b:2},{b:3}];
我不能使用 underscore.js 或 node.js 之类的东西
//example array to use
var testarr = [{a:2},{b:2},{a:1},{a:3},{b:3},{b:1}];
console.log("array sort test: should look like [{a:1},{a:2},{a:3},{b:1},{b:2},{b:3}]");
//first attempt
var sortArrayByKey = function (arr1, key) {
(arr1.sort(function(a,b){
return a[key] - b[key];}));
return arr1;
};
//still only returns testarr
console.log(sortArrayByKey(testarr, "a") );
//second attempt
var sortArrayByKey1 = function (array, key) {
var compareByKey = function (a, b) {
var x = a[key]; var y = b[key];
return x - y;
}
array.sort(compareByKey);
return array;
};
//still only returns testarr
console.log(sortArrayByKey1(testarr, “a”));
![要求图片,以防我描述错误照片