I want to make a javascript algorithm that compares the value of flight1 with the rest of two values then flight 2 with flight 1 and flight 3.
And the result should be something like dif_flight1_flight2 = 10, dif_flight1_flight3 = 110.
var x = [
['flight1', '190'],
['flight2', '200'],
['flight3', '300']
]
Store your variables and then calculate the difference based on the values. Google how to access/traverse 2d arrays in JS.
var flight1 = (x[0][1]); // 190
var flight2 = (x[1][1]); // 200
var flight3 = (x[2][1]); //300
// Note the variables can be named anything that I declared
var difference = flight2 - flight1; //difference equals 10
You can do that:
var x = [
['flight1', '190'],
['flight2', '200'],
['flight3', '300']
];
var result = [];
for(let i = 1; i < x.length; i++) {
let value = parseInt(x[0][1]) - parseInt(x[i][1]);
let element = 'diff_' + x[0][0] + '_' + x[i][0];
result.push({
key: element,
value: Math.abs(value)
});
}
This algorithm take the first element and it will be compared with the others N -1 elements. On the result array you have all the differences.
One question: Why did you use an Array of Array and not an Array of Object?
Each value must be compared with each...
function test_dif(){
var x = [
['flight1', '190'],
['flight2', '200'],
['flight3', '300']
];
var result = [];
for(let i = 0; i < x.length; i++) {
for(let c = 0; c < x.length; c++){
let value = parseInt(x[c][1]) - parseInt(x[i][1]);
let element = 'diff_' + x[c][0] + '_' + x[i][0];
result.push({
key: element,
value: Math.abs(value)
});
}
}
return result;
}
RESULT:
0: {key: "diff_flight1_flight1", value: 0}
1: {key: "diff_flight2_flight1", value: 10}
2: {key: "diff_flight3_flight1", value: 110}
3: {key: "diff_flight1_flight2", value: 10}
4: {key: "diff_flight2_flight2", value: 0}
5: {key: "diff_flight3_flight2", value: 100}
6: {key: "diff_flight1_flight3", value: 110}
7: {key: "diff_flight2_flight3", value: 100}
8: {key: "diff_flight3_flight3", value: 0}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.