admin管理员组文章数量:1253740
I'm looking for an elegant way of sorting an array by the occurrence of its elements.
For example, in:
['pear', 'apple', 'orange', 'apple', 'orange', 'apple']
the output should look like
['apple', 'orange', 'pear']
I have tried to loop through the array and save the occurrence in another temporary array, but this solution was quite bad.
I'm looking for an elegant way of sorting an array by the occurrence of its elements.
For example, in:
['pear', 'apple', 'orange', 'apple', 'orange', 'apple']
the output should look like
['apple', 'orange', 'pear']
I have tried to loop through the array and save the occurrence in another temporary array, but this solution was quite bad.
Share Improve this question edited Dec 21, 2015 at 13:53 T J 43.2k13 gold badges86 silver badges142 bronze badges asked Dec 21, 2015 at 13:23 Carle B. NavyCarle B. Navy 1,1661 gold badge11 silver badges29 bronze badges 2- You have to loop through . without looping in you can't – Ashisha Nautiyal Commented Dec 21, 2015 at 13:26
- 4 Why was your solution bad? Can you post it? – abl Commented Dec 21, 2015 at 13:27
7 Answers
Reset to default 10It would require two loops.
var arr = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
//find the counts using reduce
var cnts = arr.reduce( function (obj, val) {
obj[val] = (obj[val] || 0) + 1;
return obj;
}, {} );
//Use the keys of the object to get all the values of the array
//and sort those keys by their counts
var sorted = Object.keys(cnts).sort( function(a,b) {
return cnts[b] - cnts[a];
});
console.log(sorted);
Map the values into a fruit→count associated object:
var counted = fruits.reduce(function (acc, fruit) {
if (acc[fruit]) {
acc[fruit]++;
} else {
acc[fruit] = 1;
}
return acc;
}, {});
Map that object into a sortable array:
var assoc = counted.keys().map(function (fruit) {
return [fruit, counted[fruit]];
});
Sort the array:
assoc.sort(function (a, b) { return a[1] - b[1]; });
Extract the values:
var result = assoc.map(function (i) { return i[0]; });
You can reduce your array to remove duplicates and then sort with custom parator:
var sorted = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'].reduce(function(result, item) {
result.every(function(i) {
return i != item;
}) && result.push(item);
return result;
}, []).sort(function(i1, i2) {
return i1 > i2;
});
console.log(sorted);
With linq.js it is pretty easy (with example):
var array = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
var res = Enumerable.From(array).GroupBy(function (x) { return x; }).Select(function (x) { return { key: x.Key(), count: x.Count() } }).OrderByDescending(function (x) { return x.count }).Select(function (x) { return x.key}).ToArray();
You could try out lodash. All you need to do is group
, sort
, then map
and you are done.
var arr = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
document.body.innerHTML = _(arr).chain().groupBy()
.sortBy(function(a) {
return -a.length; // <- Note: Remove the negation to sort in ascending order.
}).map(function(a) {
return a[0];
}).value().join(', ');
<script src="https://cdn.rawgit./lodash/lodash/master/dist/lodash.js"></script>
Try this:
var arr = ['pear', 'apple', 'orange', 'apple', 'orange', 'apple'];
var result = [];
var count = 0;
arr.sort();
for (var i = 0; i < arr.length; i++) {
count++;
if (arr[i] != arr[i + 1]) {
result.push({
"count": count,
"value": arr[i]
});
count = 0;
}
}
result.sort(function(a, b) {
if (a.count < b.count) return 1;
if (a.count > b.count) return -1;
return 0;
});
console.log(result.map(function(item){return item.value}));
For a legacy JS version i ended up with this.
function sortByOccurrence(arr_in){
var arr_out = [];
var c = {}; // count obj
for (var i = 0; i < arr_in.length; i++) {
var p = arr_in[i];
c[p] = (c[p] || 0) + 1;
}
for (var p in c) if ( c.hasOwnProperty(p) ) arr_out.push(p);
arr_out.sort(function(a, b) { return c[b] - c[a];});
return arr_out;
}
本文标签: javascriptSort Array by occurrence of its elementsStack Overflow
版权声明:本文标题:javascript - Sort Array by occurrence of its elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740777694a2284557.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论