代码之家  ›  专栏  ›  技术社区  ›  Romano

从数组中获取最高但也是唯一的数字

  •  0
  • Romano  · 技术社区  · 10 年前

    我有个问题。我正在寻找一种方法来获得数组的最大唯一数。

    var temp = [1, 8, 8, 8, 4, 2, 7, 7];
    

    现在我想得到输出4,因为这是唯一的最高数字。

    有好的&希望是一条捷径吗?

    3 回复  |  直到 10 年前
        1
  •  2
  •   Tushar    10 年前

    是的,有:

    Math.max(...temp.filter(el => temp.indexOf(el) == temp.lastIndexOf(el)))
    

    说明:

    1. 首先,使用 Array#filter

      temp.filter(el => temp.indexOf(el) === temp.lastIndexOf(el)) // [1, 4, 2]
      
    2. 现在,使用ES6从数组中获取最大值 spread operator

      Math.max(...array) // 4
      

      此代码等效于

      Math.max.apply(Math, array);
      
        2
  •  1
  •   NickT    10 年前

    如果你不想变得花哨,你可以使用排序和循环来检查最小数量的项目:

    var max = 0;
    var reject = 0;
    
    // sort the array in ascending order
    temp.sort(function(a,b){return a-b});
    for (var i = temp.length - 1; i > 0; i--) {
      // find the largest one without a duplicate by iterating backwards
      if (temp[i-1] == temp[i] || temp[i] == reject){
         reject = temp[i];
         console.log(reject+" ");
      }
      else {
         max = temp[i];
         break;
      }
    
    }
    
        3
  •  0
  •   Community Mohan Dere    9 年前

    使用排列运算符,您可以轻松找到最高数字

    Math.max(...numArray);
    

    然后剩下的唯一事情是预先从数组中筛选重复项,或者如果重复项,则删除与最大数量匹配的所有元素。

    在这样的es6中,删除beforeHand是最简单的。

    Math.max(...numArray.filter(function(value){ return numArray.indexOf(value) === numArray.lastIndexOf(numArray);}));
    

    对于非es6兼容的删除重复项的方法,请查看 Remove Duplicates from JavaScript Array ,第二个答案包含了对几个备选方案的广泛检查