簡體   English   中英

從數組中獲得最高但也是唯一的數字

[英]Get the highest but also unique number from an array

我有個問題。 我正在尋找一種獲取數組的最大唯一編號的方法。

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

剩下的唯一事情就是事先從數組中過濾掉重復項,或者如果它是重復項,則刪除所有與最大數匹配的元素。

在ES6中像這樣刪除beforeHand將是最簡單的。

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

對於非es6兼容的刪除重復項的方法,請查看從JavaScript數組刪除重復項 ,第二個答案包含對幾種替代方案的詳盡檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM