I need to browse and compare two array and get the following result : For example:
T = [5,10,15];
V = [15,50,30];
I need to return the following values:
V[0]-T[0] = 15-5 = 10
V[1]-T[0] = 50-5 = 45
V[2]-T[0] = 30-5 = 25
V[0]-T[1] = 15-10 = 5
V[1]-T[1] = 50-10 = 40
V[2]-T[1] = 30-10 = 20
V[0]-T[2] = 15-15 = 0
V[1]-T[2] = 50-15 = 35
V[2]-T[2] = 30-15 = 15
The MAX of the three value = 35
I tried to do it by myself using this code:
var T = [5,10,15];
var V = [15,50,30];
var X;
for (var i = 0; i < T.length; ++i){
for (var j = 0; j < V.length; ++j)
{
X = V[j]-T[i];
console.log(V[j]-T[i]);
}
if ((V[j]-T[i]) >= X)
{
X = V[j]-T[i];
console.log(V[j]-T[i]);
}
else
{
console.log(X);
}
console.log('\n');
}
But i get the following result:
10
45
25
25
5
40
20
20
0
35
15
15
You could map t and take the maximum value of the mapped values of the subtraction.
This proposal features Array#map with arrow functions and Math.max with spread syntax ... for an array for taking it as parameters.
var t = [5, 10, 15],
v = [15, 50, 30],
max = t.map(tt => Math.max(...v.map(vv => vv - tt)));
console.log(max);
ES5
var t = [5, 10, 15],
v = [15, 50, 30],
i, j,
max,
result = [];
for (i = 0; i < t.length; i++) {
max = v[0] - t[i]; // take the first value of v
for (j = 1; j < v.length; j++) { // iterate from the second value of v
max = Math.max(max, v[j] - t[i]); // get max value
}
result.push(max); // store max
}
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With