我想对数组元素进行排序

时间:2016-04-05 21:49:23

标签: javascript node.js

假设我有如下数组

ifdef HOME
    $(info $$HOME is $(HOME))
else        
    $(info $$HOME is undefined)
endif

然后结果应该是

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

JavaScript或nodejs中的必需实现

4 个答案:

答案 0 :(得分:3)

我在lodash中使用了jsbin example和纯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的排序不同,因为没有为具有相同计数的数字指定排序顺序。 / p>

上面所做的是创建了number=>count的地图(例如{ "1": 3, "5": 3 }),然后将它们配对为元组(因为对象无法在JavaScript中进行确定性排序:{{1} })。然后,我们只是根据计数对元组集合进行排序,并映射元组集合以仅返回数字(例如[["1", 3], ["5", 3]])。

答案 1 :(得分:3)



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);




答案 2 :(得分:2)

以下是一种方法: JSBIN:https://jsbin.com/josuwir/1/edit?js,console

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

var c = array.reduce(function(a, b) {
  a[b] = ++a[b] || 1;
  return a;
}, {});


var keys = Object.keys(c);


var nn = keys.sort(function(a, b) {
  if (c[a] < c[b]) {
    return 1;
  } else {
    return -1;
  }
}).map(function(a) {return Number(a)});

答案 3 :(得分:1)

function sortArray(array) { 

    var reducedArray = array.filter(function(item, pos) { //A copy without duplicates
       return array.indexOf(item) == pos;
    })

    var elementFreq = {} //Object that contains element frequencies
    for (var i=0; i<reducedArray.length; i++) {
        var count = 0;
        for (var j=0; j<array.length; j++) {
            if (array[j] == reducedArray[i]) {
                count++;
            }
        }
        elementFreq[array[i]] = count;
    }

    function compare(a,b) { //compares the frequency of two elements
        return elementFreq[b]-elementFreq[a]
    }

    reducedArray.sort(compare) //sorts reducedArray based using compare function

    return reducedArray 
}