我正在尝试在JS中对对象进行排序,但sort函数似乎对我的对象不起作用。
我想按频率对数组进行排序,降序。
["B", "A", "C", "C", "A"]
将导致[C: 2, A: 2, B: 1]
这是一个小提琴:http://jsfiddle.net/64q43/
var arr = ["B", "A", "C", "C", "A"];
var arrFrequency = [];
arr.forEach(function(value) {
arrFrequency[value] = 0;
});
console.log(arrFrequency);
// [B: 0, A: 0, C: 0]
arr.filter(function(value) {
if (arrFrequency.hasOwnProperty(value)) arrFrequency[value]++;
});
console.log(arrFrequency);
// [B: 1, A: 2, C: 2]
答案 0 :(得分:1)
对象没有任何已定义的订单。但是,您可以先创建一个这样的对象:
var arr = ["B", "A", "C", "C", "A"];
var freq = {};
arr.forEach(function(value) {
freq[value] = (freq[value] || 0) + 1;
});
console.log(freq); // {B: 1, A: 2, C: 2}
然后将此对象的键映射到数组:
var arrFrequency = [];
for(var k in freq) {
arrFrequency.push({ key: k, count: freq[k] });
};
console.log(arrFrequency); // [{"key":"B","count":1},{"key":"A","count":2},{"key":"C","count":2}]
现在就这样排序:
arrFrequency.sort(function(x, y) {
return y.count - x.count;
});
console.log(arrFrequency); // [{"key":"A","count":2},{"key":"C","count":2},{"key":"B","count":1}]
答案 1 :(得分:0)
我的这种排序功能可以帮助您:
// sort objects according to their key-names (a,b,c):
function sortObjArray(array){
for(var k=1; k < array.length; k++){
for(var i=k; i > 0; i--){
var formerLetter = Object.keys(array[i-1]);
var currLetter = Object.keys(array[i]);
if( currLetter < formerLetter ){
[x,y] = [array[i],array[i-1]];
[array[i],array[i-1]] = [y,x];
}
}
}
return array;
}
var array = [{ b: 4},{ c: 1},{ a: 3}];
sortObjArray(array);//[Object { a=3}, Object { b=4}, Object { c=1}]
// or in descending order, according to their occurrence
function sortObjArray2(array){
for(var k=1; k < array.length; k++){
for(var i=k; i > 0; i--){
var formerLetter = Object.keys(array[i-1])[0];
var currLetter = Object.keys(array[i])[0];
var formerValue = array[i-1][formerLetter];
var currValue = array[i][currLetter];
if( currValue> formerValue ){
[x,y] = [array[i],array[i-1]];
[array[i],array[i-1]] = [y,x];
}
}
}
return array;
}
var array = [{ b: 4},{ c: 1},{ a: 3}];
sortObjArray2(array);//[Object { b=4}, Object { a=3}, Object { c=1}]