试图从一个只包含整数的数组中获得最大值和最小值似乎比我想象的要难。

var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray)

我希望这是99 104 140000。相反,它显示的是104、14万、99。看起来排序是把值当做字符串处理的。

有没有办法让排序函数对整数值进行排序?


当前回答

提升

arr.sort((a, b) => a - b);

下行

arr.sort((a, b) => b - a);

只是为了好玩:

降序=升序+反转

arr.sort((a, b) => a - b).reverse();

其他回答

sort_mixed

Object.defineProperty(Array.prototype,"sort_mixed",{
    value: function () { // do not use arrow function
        var N = [], L = [];
        this.forEach(e => {
            Number.isFinite(e) ? N.push(e) : L.push(e);
        });
        N.sort((a, b) => a - b);
        L.sort();
        [...N, ...L].forEach((v, i) => this[i] = v);
        return this;
    })

try a =[1,'u',"V",10,4,"c"," a "].sort_mixed();console.log (a)

数组中。Sort默认使用字母排序,而不是数字排序。

要支持数字,请添加如下的like

var numArray = [140000, 104, 99];
numArray.sort((a, b) =>  a - b); // <-- Ascending
numArray.sort((a, b) =>  b - a); // <-- Descending
console.log(numArray);

输出:

Let grade =[80,100,50,90,40]; grade.sort ((x, y) = > x - y); grade.forEach(元素= > console.log(元素));

如果你需要从字符串列表中计算和排序最大的charCodeAt,这是正确的方法。

const arrayLines = '1.1.1.1\n1.0.1.1\n1.1.1.2\n1.1.1.0'.split('\n');

// Response: (4) ['1.0.1.1', '1.1.1.0', '1.1.1.1', '1.1.1.2']
arrayLines.sort((a, b) => {
    let a_charCodeSize = 0,
        b_charCodeSize = 0;

    // Loop true a & b characters and calculate the charCodeAt size.
    for (const aChar of a) a_charCodeSize += aChar.charCodeAt(0);
    for (const bChar of b) b_charCodeSize += bChar.charCodeAt(0);

    return a_charCodeSize - b_charCodeSize;
});

试试下面的代码:

HTML:

<div id="demo"></div>

JavaScript代码:

<script>
    (function(){
        var points = [40, 100, 1, 5, 25, 10];
        document.getElementById("demo").innerHTML = points;
        points.sort(function(a, b){return a-b});
        document.getElementById("demo").innerHTML = points;
    })();
</script>