Search code examples
javascriptarraysloopscomparereturn-value

why after applying my function to the array it returns the same array?


I'm looping over an array with my function compare to get the max number of temperature from the array but there was no any changes after applying the function to the array temperature.

let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];

function compare(temperature) {
  let i = 0;

  for (i = 0; i < temperature.length; i++) {
if (typeof temperature[i] === "string") temperature.splice(i, 1);
  }

  for (let k = i + 1; k < temperature.length; k++) {
if (temperature[i] < temperature[k]) Array.splice(i, 1);
else if (temperature[i] > temperature[k]) Array.splice(k, 1);
  }
  return temperature;
}

console.log(temperature);


Solution

  • You can achieve this with a single line of code by using Math.max() on array.

    Working Demo :

    // Input array
    let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
    
    // Math.max() to get maximum number element from an array.
    const maxTemp = Math.max(...temperature.filter(elem => typeof elem !== 'string'));
    
    // Result
    console.log(maxTemp);