Reputation: 6320
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>");
}
Upvotes: 0
Views: 118
Reputation: 72857
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
.
Upvotes: 3
Reputation: 84
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
Upvotes: 0
Reputation: 11317
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]);
}
Upvotes: 1