0

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']
]
Beez
  • 478
  • 9
  • 23
CoderCoder42
  • 171
  • 2
  • 11

3 Answers3

0

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
Beez
  • 478
  • 9
  • 23
  • You could also traverse the array using a loop and doing the calculations in the loop check out this [link](https://stackoverflow.com/questions/10021847/for-loop-in-multidimensional-javascript-array) – Beez Oct 16 '19 at 18:30
0

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?

Simone Boccato
  • 199
  • 1
  • 14
0

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}
CoderCoder42
  • 171
  • 2
  • 11