我想对数组的元素进行排序[关闭]

假设我有如下数组

var array=[3,4,5,5,5,6,8,3,12,1,1,1];

然后结果应该是

array=[5,1,3,4,6,8,12];

JavaScript或nodejs中必需的实现


哔哔one
浏览 682回答 4
4回答

摇曳的蔷薇

我在这个jsbin示例中使用了lodash和普通JavaScript数组方法的组合:var arr = [3,4,5,5,5,6,8,3,12,1,1,1];var sorted = _.sortBy(_.toPairs(arr.reduce(function(agg, curr) {   agg[curr] = agg[curr] ? agg[curr] + 1 : 1;   return agg;}, {})), function(pair) {   return -pair[1];}).map(function(pair) {   return pair[0];});console.log(sorted); // => ["1", "5", "3", "4", "6", "8", "12"]但是,排序顺序"5"和顺序"1"不同3,4,6,8,12,因为没有为具有相同计数的数字指定排序顺序。上面所做的是创建number=>count(例如{ "1": 3, "5": 3 })的映射,然后将它们配对为元组(因为对象不能在JavaScript中确定性地排序:) [["1", 3], ["5", 3]]。然后,我们简单地根据计数对元组集合进行排序,并映射元组集合以仅返回数字(例如["1", "5", /* etc. */ ])。

肥皂起泡泡

var array = [3, 4, 5, 5, 5, 6, 8, 3, 12, 1, 1, 1];var obj = {};array.forEach(e => obj[e] = obj[e] + 1 || 1);var sorted = Object.keys(obj)     .map(e => ({ n: e, times: obj[e] }))     .sort((a, b) => b.times - a.times)     .map(e => e.n);document.write(sorted);

largeQ

function sortArray(array) {&nbsp;&nbsp; &nbsp; var reducedArray = array.filter(function(item, pos) { //A copy without duplicates&nbsp; &nbsp; &nbsp; &nbsp;return array.indexOf(item) == pos;&nbsp; &nbsp; })&nbsp; &nbsp; var elementFreq = {} //Object that contains element frequencies&nbsp; &nbsp; for (var i=0; i<reducedArray.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var count = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (var j=0; j<array.length; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array[j] == reducedArray[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; elementFreq[array[i]] = count;&nbsp; &nbsp; }&nbsp; &nbsp; function compare(a,b) { //compares the frequency of two elements&nbsp; &nbsp; &nbsp; &nbsp; return elementFreq[b]-elementFreq[a]&nbsp; &nbsp; }&nbsp; &nbsp; reducedArray.sort(compare) //sorts reducedArray based using compare function&nbsp; &nbsp; return reducedArray&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript