在数组javascript中查找最大重复数的总和

时间:2018-05-21 09:02:31

标签: javascript arrays sorting

我试图在数组中找到最大的重复数字并对其求和。

在这里经历的时候,我找到了找到最大数量的解决方案。但是现在我需要计算有多少个最大(最大)数字,并存储最大数量然后求和。

示例: - 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

5 个答案:

答案 0 :(得分:4)

这将返回具有指定输出{max: 9, items: [9,9,9], sum: 27}的对象。

&#13;
&#13;
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]))
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用Math.max获取最大值,然后使用filter&amp; reduce总和值

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

答案 2 :(得分:1)

您可以计算值,减少最大计数并返回值和计数的乘法。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

如果你从一个数组开始,那么你只需要 reduce 来找到最大值并返回总和,例如

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 4 :(得分:1)

你可以在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);