matriz de comparação in javascript

To create a matrix of comparison using nested arrays in JavaScript, you can follow these steps:

  1. Define an array of data you want to compare, and the number of elements to be compared. For demonstration purposes, we will compare the height of three different people.
index.tsx
const peopleHeight = [165, 172, 189];
const numberOfPeople = peopleHeight.length;
82 chars
3 lines
  1. Create an empty 2-dimensional array, with dimensions numberOfPeople x numberOfPeople.
index.tsx
const comparisonMatrix = new Array(numberOfPeople).fill(0).map(() => new Array(numberOfPeople).fill(0));
105 chars
2 lines
  1. Use two nested loops to compare each element with every other element, and assign a value in the matrix based on the comparison.
index.tsx
for (let i = 0; i < numberOfPeople; i++) {
  for (let j = 0; j < numberOfPeople; j++) {
    if (peopleHeight[i] < peopleHeight[j]) {
      comparisonMatrix[i][j] = -1;
    } else if (peopleHeight[i] > peopleHeight[j]) {
      comparisonMatrix[i][j] = 1;
    }
  }
}
266 chars
10 lines

In this example, we are assigning a value of 1 if the height of person i is greater than person j, -1 if the height of person i is less than person j, and 0 if they are equal.

  1. The resulting matrix will look like this:
index.tsx
[[0, -1, -1],
 [1, 0, -1],
 [1, 1, 0]]
39 chars
4 lines

This matrix represents the relative height comparison between the three people. For example, the value -1 in position [0][1] means that person 0 is shorter than person 1. The matrix is also symmetric, as it should be, since the comparison operation is commutative.

gistlibby LogSnag