lowest and highest number with for loop

33 Views Asked by At

I am trying to filter an array and find the highest and lowest number (one highest and lowest, if 1 is two times and it's lowest only first one should be taken out from the array, same for the highest) and then with a for loop sum up the rest of the numbers from the array.

First I am trying to find the min and max numbers in the array with Math.min and Math.max and also indexes of them in the array.

I will write the code below it works correctly in the first example but not in the second example.

function sumArray(array) {
  let newArr = array;
  let smallest = Math.min(...newArr);
  let realSmall = array.indexOf(smallest);

  let highest = Math.max(...newArr);
  let realHigh = array.indexOf(highest);
  let sumUp = 0;
  for (let i = 0; i < newArr.length; i++) {
    if (newArr[i] !== array[realSmall]) {
      if (newArr[i] !== array[realHigh]) {
        sumUp = sumUp + newArr[i];
      }
    }
  }
  return sumUp;
}

sumArray([6, 2, 1, 8, 10]);

sumArray([0, 1, 6, 10, 10]);

In the first example, so, I am checking if newArr[i] is different from array[realSmall] - here I am getting the number itself, not the index, and therefore I want to compare newArr[i] to the index itself where this math.min or math.max is located, because in the second example when there is two 10 it returns the wrong result, because array[realHigh]) is 10 in 2 iteration and i want to take out only one lowest, so the result should be 17 not 7, because of that I want to make compare newArr[i] to the index where math.min or max is located and not the result that I am getting from array[realHigh].

I hope i was clear, i already solved this kata but another way, I just want to know how to compare to the index itself, for example newArr[i[ must be different from the index where first ten is located (index of 3 not the result of the array[realHigh] which is 10).

0

There are 0 best solutions below