0

I have two dynamic array which can be like

arr1 = [4, 17, 12, 11];
arr2 = [11, 10, 23, 11];

now I need to always save the bigger numbr on #cal-box-1-1 and smaller on #cal-box-1-2 to deduct smaller number from the bigger number

for (i = 1; i < arr1.length; i++) { 
   $(".map").append('<div class="mapper"><div id="cal-box-1-'+i+'"></div><div id="cal-box-1-'+i+'"></div></div>");
}
Behseini
  • 6,066
  • 23
  • 78
  • 125

3 Answers3

3

If you always want to subtract the lower number from the highest number, you can do this:

var result = Math.abs(value1 - value2);

It doesn't matter which of the 2 is the highest value:

10 - 7 === 3;      // Correct order
Math.abs(3) === 3;  // Value doesn't change.

7 - 10 === -3;     // Wrong order,
Math.abs(-3) === 3; // But Math.Abs fixes that.

-7 - -10 === 3;    // Correct order (-10 is smaller than -7)
Math.abs(3) === 3;  // Value doesn't change.

-10 - -7 === -3;   // Wrong order,
Math.abs(-3) === 3; // But Math.Abs fixes that.

Because you'll always be subtracting the lowest value from the highest value, you will always get a result that's >= 0.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
1

What about this code to determine which number is bigger or smaller:

for (i = 0; i < arr1.length; i++) { // I assume you want to start with the first element
   var bigger = Math.max(arr1[i], arr2[i]);
   var smaller = Math.min(arr1[i], arr2[i]);
}
lex82
  • 11,173
  • 2
  • 44
  • 69
0

Are you asking to find the largest number and the smallest number and then subtract the two?

Math.max(...arr1.concat(arr2)) - Math.min(...arr1.concat(arr2))
arr1.concat(arr2) => [10, 11, 11, 11, 12, 17, 23, 4]
Math.max(...arr1.concat(arr2)) => 23
Math.min(...arr1.concat(arr2)) => 4
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
richessler
  • 84
  • 6
  • The OP does not hint that he may be using ES6. You're also using quite a few "heavy" operations to do something that's quite simple. – Cerbrus Dec 01 '15 at 07:42