簡體   English   中英

在數組javascript中查找最大重復數的總和

[英]Find sum of largest repeated number in an array javascript

我試圖在數組中找到最大的重復數並求和。

在這里瀏覽時,我找到了找到最大數量的解決方案。 但是現在我需要計算最大(最大)數量並存儲最大數量,然后求和。

示例:-array- [5,5,7,9,9,9]。 因此最大數量是9,所以是3倍,它將存儲在另一個數組[9,9,9]中,總計= 27。

我得到這個來找到數組中的最大數目:-

function evaluate() {
  const input = prompt("Please enter the array of integers in the form: 1,2,3,1")
    .split(',')
    .map(nums => nums.trim());

  function max(numArray) 
{
    var nums = numArray.slice();
    if (nums.length == 1) { return nums[0]; }
    if (parseInt(nums[0]) < parseInt(nums[1])) { nums.splice(0,1); }
    else { nums.splice(1,1); }    
    return max(nums);
}


  if (input == "" || input == null) {
            document.writeln("Sorry, there is nothing that can be calculated."); 
        } else {    

  document.writeln("The largest number is: ");
  document.writeln(max(input) + " with a starting input string of: " + input);
}
}
evaluate();

因此,我希望上述示例顯示的最終輸出為27

這將返回具有指定輸出{max: 9, items: [9,9,9], sum: 27}

 function maxElementSum(arr) { var max = Math.max(...arr) var count = arr.filter(el => el == max).length return {max: max, items: Array(count).fill(max), sum: max * count} } console.log(maxElementSum([5,5,7,9,9,9])) 

使用Math.max來獲得最大值,然后使用filterreduce求和

 // find the largest number var _gt = Math.max(...[5, 5, 7, 9, 9, 9]) // then filter the array and get the largest values // and use reduce to sum the numbers var arr = [5, 5, 7, 9, 9, 9].filter(function(item) { return _gt === item }).reduce(function(acc, curr) { acc += curr; return acc; }, 0); console.log(arr) 

您可以對值進行計數,減少最大計數,然后返回值與計數的乘積。

 var array = [5, 5, 7, 9, 9, 9], max = Object .entries( array.reduce((r, v) => (r[v] = (r[v] || 0) + 1, r), Object.create(null)) ) .reduce((a, b) => a[1] > b[1] ? a : b) .reduce((a, b) => a * b); console.log(max); 

如果從數組開始,則只需要減少即可找到最大值並返回總和,例如

 var nums = [5,5,7,9,9,9], max = -Infinity, result = nums.reduce((acc, num) => num > max? acc = max = num : num == max? acc += num : acc, 0); console.log('Result: ' + result); 

您只需在O(n)時間內使用一個forEach循環即可輕松完成此操作,

var array = [5, 5, 7, 9, 9, 9];
var max = array[0], total = 0;
array.forEach((a)=>{
  if(a==max){
    total+=max;
  }
  else if(a>max){
    max = total = a;
  }
});
console.log("total:"+total);  

暫無
暫無

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

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