【问题标题】:How can I sort an array with numeric and string values?如何使用数字和字符串值对数组进行排序?
【发布时间】:2022-11-26 06:57:28
【问题描述】:

有一个数组[350, 456, "Not Found"]。我想对它进行排序,并且我想获得最低值(350)。你能帮忙吗?


    var urunAdi = [350, 456, "NotFound"];
    urunAdi.sort(function(a,b){return a-b});
    var lowestPrice = urunAdi[0];

像这样排序后(350 - 456 - “NotFound”),我希望它找到 350 作为最低值。

【问题讨论】:

    标签: javascript arrays sorting


    【解决方案1】:

    您可以为 filter 元素创建自定义函数,如果它们是 string 或数字,并返回基本上合并这些数组的 concat

    myArr = [456, 350, "Not Found"]
    
    function sortMe(arr) {
      let numArr = arr.filter((el) => typeof el === "number").sort((a, b) => a - b);
      let strArr = arr.filter((el) => typeof el === "string").sort();
      return numArr.concat(strArr);
    }
    
    console.log(sortMe(myArr));

    【讨论】:

      【解决方案2】:

      这可以通过几个 Array 方法轻松完成:

      const urunAdi = [350, 456, 'NotFound'];
      
      const getLowestNumber = (arr) => {
        return arr.filter((data) => typeof data === 'number').sort()[0];
      };
      
      const lowestPrice = getLowestNumber(urunAdi);
      

      希望这可以帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多