title: Mini-Max Sum In JavaScript - How to Get the Minimum Sum And Maximum Sum of 4 Elements in a 5-Element Array
body: <p><a href="https://www.hackerrank.com/challenges/mini-max-sum/problem?utm_campaign=challenge-recommendation&amp;utm_medium=email&amp;utm_source=24-hour-campaign" rel="nofollow noreferrer">Link to HackerRank Challenge</a></p>
  
  <p>My idea is to loop through the array and sum all elements in the array except for one element each time, then find the smallest sum and the largest sum. </p>
  
  <p>I know that <code>.splice()</code> can remove any element from an array. But currently, with my code, it's only removing one element from the array <strong>once</strong>. I.e. this is only giving me one chunk:</p>
  
  <pre><code>function miniMaxSum(arr) {
  
    let smallestSum = 0;
    let largestSum = 0;
  
    for (let i = 0; i &lt; arr.length; i++) {
      let chunk = arr.splice(1);
      console.log(chunk);
      if (chunk &gt; largestSum) largestSum = chunk;
      if (chunk &lt; smallestSum) smallestSum = chunk;
    }
    return (smallestSum, largestSum);
  }
  </code></pre>
  
  <p>I need to remove one element from the array <strong>every time</strong> while looping, then get the max and min sums from that array. </p>
  
  <p>So for given array of <code>[1, 2, 3, 4, 5]</code></p>
  
  <p>I should get the following possible "chunks": </p>
  
  <p><code>[2, 3, 4, 5]</code>, <code>[1, 3, 4, 5]</code>, <code>[1, 2, 4, 5]</code>, <code>[1, 2, 3, 5]</code>, <code>[1, 2, 3, 4]</code>. </p>
  
  <p>The chunk with the highest sum is <code>[2, 3, 4, 5]</code></p>
  
  <p>And the chunk with the smallest sum is <code>[1, 2, 3, 4]</code>. </p>
  
  <p>How can I adjust my code to get all of the possible 4-digit arrays within the given array so that I can compare their sums, still using a for-loop? Or if not with a for-loop, what else would you suggest?</p>
  
  <p><strong>EDIT</strong>: Now using <code>Math.min()</code> and <code>Math.max()</code> to get the smallest and largest elements in the array. Then using <code>.filter()</code> to remove those elements in order to create new arrays. Then getting the sums of those arrays.</p>
  
  <pre><code>function miniMaxSum(arr) {
  
    let smallest = Math.min(...arr);
    let largest = Math.max(...arr);
  
    let smallestArray = arr.filter(element =&gt; element !== largest);
    let largestArray = arr.filter(element =&gt; element !== smallest);
  
    let sumOfSmallestArray = 0;
    let sumOfLargestArray = 0;
  
    for (let i = 0; i &lt; smallestArray.length; i++) {
      sumOfSmallestArray += smallestArray[i];
    }
  
    for (let i = 0; i &lt; largestArray.length; i++) {
      sumOfLargestArray += largestArray[i];
    }
  
    return ([sumOfSmallestArray, sumOfLargestArray]).toString();
  }
  
  </code></pre>
  
  <p>But even though it works in my console, it doesn't work in HackerRank.</p>