Home > database >  How can I do arithmetic with my Array elements if some of them are negative?
How can I do arithmetic with my Array elements if some of them are negative?

Time:02-05

So I am trying to collect a maximum and minimum value from an array.

After this collection,and passing the maximum and minimum elements as arguments into my function, I see that the negative values are getting their signs changes.

e.g

10 - -6 = 16 (based on normal sign change in Maths);

when I should have a 4 (i.e 4). I need this to complete my function which does the subtraction of the maximum and minimum value. This is my code snippet in case it is needed.

const temperatures = [3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];
const calcTempAmplitude = function(temperatures) {
  let maxTemp = temperatures[0];
  let minTemp = temperatures[0];
  for (let i = 0; i < temperatures.length; i  ) {
    const curTemp = temperatures[i];
    if (typeof curTemp !== 'number') continue;
    if (curTemp > maxTemp) maxTemp = temperatures[i];
    if (curTemp < minTemp) minTemp = temperatures[i];
  }
  console.log(maxTemp, minTemp);
  const TempAmplitude = maxTemp - minTemp;
  return TempAmplitude;
};
console.log(calcTempAmplitude(temperatures));

CodePudding user response:

You can just use Math.abs() for your negative temperature, which will return the absolute value of an int value.

const TempAmplitude = maxTemp - Math.abs(minTemp);

const temperatures = [3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];
const calcTempAmplitude = function(temperatures) {
  let maxTemp = temperatures[0];
  let minTemp = temperatures[0];
  for (let i = 0; i < temperatures.length; i  ) {
    const curTemp = temperatures[i];
    if (typeof curTemp !== 'number') continue;
    if (curTemp > maxTemp) maxTemp = temperatures[i];
    if (curTemp < minTemp) minTemp = temperatures[i];
  }
  //console.log(maxTemp, minTemp);
  const TempAmplitude = maxTemp - Math.abs(minTemp);
  return TempAmplitude;
};
console.log(calcTempAmplitude(temperatures));

  • Related