0

Hello I have five values I am trying to add the 4 highest values in the array and the 4 lowest values in the array. For example var arr = [3, 1, 5, 7, 9]; Adding the highest values would be 3 + 5 + 7 + 9. The min Sum would be 1 + 3 + 5 + 7. I am having one problem. I sorted the array in ascending order. For logged the maxSum and all the maxSum values were showing up in the console [3,5,7,9]. I removed the first value (1) maxSum[0]. And summed up the rest in the array. Only the last value is showing up when I remove the minSum = sorted.slice(-1) which 9; I want the rest to show up so I can sum up the minSum of the array. Secondly there must be a much shorter and better way of doing this.

var arr = [3, 1, 5, 7, 9];  
//Arranged var arr = [1, 3, 5, 7, 9];

totalMaxSum = 0;
totalMinSum = 0;
    
function miniMaxSum(arr)  {

var sorted = arr.sort(function(a, b){return a - b});
   
      var maxSum = sorted.slice(1);
      var minSum = sorted.slice(-1);

      console.log(maxSum);
      console.log("Minimum " + minSum);
      for(var count = 0; count < maxSum.length; count++) {

         totalMaxSum += maxSum[count];
         

      }
   
      console.log("totalMax " + totalMaxSum);
           
      for(var countess = 0; countess < minSum.length; countess++) {

         
         
      }
   
   }


miniMaxSum(arr);
mustyg123
  • 17
  • 5
  • `var minSum = sorted.slice(-4);` to get the last 4 into an array, then all you need to do is sum up the numbers in it, like you're already doing with the `for` loop (or you could use `.reduce((a, b) => a + b, 0)`) – CertainPerformance Jun 22 '22 at 23:12
  • The problem is not with extracting the last elements -- that is done correctly with `.slice(1)`. The problem is with extracting the **first** elements. That *should* be done with `.slice(0, -1)`, not `.slice(-1)`. – trincot Jun 22 '22 at 23:14
  • I tried -4 before asking the question and it came up with the last 4 numbers and excluded 1. (0,-1) works. Thank you – mustyg123 Jun 22 '22 at 23:22

0 Answers0