人们!
我想将originalArray转换为finalArray,如下所示。
任何人都可以提前帮助,谢谢。
正如你所看到的,我想按" cnt_bought"排序,比如" Sam"," Alice"
var originalArray = [
{"name":"Sam","cnt_bought":0},
{"name":"John","cnt_bought":5},
{"name":"Alice","cnt_bought":0},
{"name":"Bob","cnt_bought":31}
];
var finalArray = [
{"cnt_bought":0, "name" : ["Sam","Alice"]},
{"cnt_bought":5, "name" : ["John"]},
{"cnt_bought":31, "name" : ["Bob"]}
];
答案 0 :(得分:1)
试试这个:
function mapAndSortArray(originalArray) {
var finalArray = [];
while (originalArray.length > 0) {
var found = false;
var next = originalArray.shift();
for (var i = 0; i < finalArray.length; i++) {
if (next.cnt_bought === finalArray[i].cnt_bought) {
finalArray[i].name.push(next.name);
found = true;
break;
}
}
if (! found) {
next.name = [next.name];
finalArray.push(next);
}
}
finalArray.sort(function(a, b) {
var tbr = 0;
if (a.cnt_bought < b.cnt_bought) {
tbr = -1;
}
else if (a.cnt_bought > b.cnt_bought) {
tbr = 1;
}
return tbr;
});
return finalArray;
}