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

Get the highest but also unique number from an array

本文关键字:唯一 数字 数组 获取      更新时间:2023-09-26

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

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

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

有好的&希望能走很短的路?

是的,有:

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扩频算子从阵列中获得最大数字

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

    此代码相当于

    Math.max.apply(Math, array);
    

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

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

使用排列运算符可以很容易地找到的最高数字

Math.max(...numArray);

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

beforeHand在es6中是最简单的。

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

对于非es6兼容的删除重复项的方法,请查看从JavaScript数组中删除重复项,第二个答案包含对几种替代方案的广泛检查