【问题标题】:How to get maximum value of alphanumeric of an array in reactjs如何在reactjs中获取数组的字母数字的最大值
【发布时间】:2022-08-18 00:43:31
【问题描述】:

如何在 REACTJS 中使用字母数字字符串获取此数组的最大值?

我想要输出:

ABC113

试过:

const arr = [\'ABC111\',\'ABC112\', \'ABC113\']
const latestArr = Math.max(arr)
console.log(latestArr)

    标签: reactjs arrays json


    【解决方案1】:
    1. 是什么让这些字符串比另一个更大,它们是以 16 为基数还是什么?当前格式是非数字的,不能作为数字进行比较。如果它们是基数 16,则使用 parseInt('abc123',16) 将它们设为数字

      如果它们被格式化为数组中的数字,那么您可以使用Math.max 获得最大值,如下所示:

      const arr = [1,2,3];
      const max = Math.max(...arr);
      console.log(max);

      如果数组中的值不是数字格式,您可以编写自定义解决方案来比较值并获取最大值。

      const arr = ['ABC111','ABC112', 'ABC113'];
      const max = arr.reduce(function(prevMax, curVal) {
          // Replace this with logic needed to compare values
          return curVal > prevMax ? curVal : prevMax;
      }, '0'); // Need to replace this base case with lowest possible value
      console.log(max);

    【讨论】:

      【解决方案2】:

      如果它只是一个单维字符串数组,您可以对数组进行排序并获取最后一个元素。但是,如果值不是一致的大写,则必须考虑区分大小写。所以如果数组有'abc110',那将显示为最大值。为了使它不区分大小写,您可以在排序之前添加一个 .map(ele => ele && ele.toUpperCase()) 。如果您的数组有空值,那么您可以先使用 arr.filter 删除它们。

      const arr = ['ABC111','ABC112', 'ABC113'];
      const sortedarr = arr.map(ele => ele && ele.toUpperCase()).sort() ;
      const maxValue = sortedarr[sortedarr.length -1];
      console.log(maxValue);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-02
        • 1970-01-01
        • 2013-01-19
        相关资源
        最近更新 更多