How to compare arrays to javascript?

Asked

Viewed 3,984 times

2

I have an array that I get from the checkboxes that the user chooses

const check_frutas = ["banana", "uva", "pera"];

And in my code, I need to compare this array with others to get the most similar.

const frutas_a = ["banana", "limao", "pera", "goiaba"];
const frutas_b = ["tomate", "tangerina", "pera", "melancia"];

How do I make this comparison to get a result like "The most similar array is fruit_b"?

5 answers

3

Make the intersection between the input set and the other sets and check the amount of items resulting from this operation.

Below is an example of implementation.

Note that this implementation doesn’t take into account performance issues (you probably don’t even want to care about it working with such small arrays). Therefore, the solution has an O(n²) runtime - a loop in the filter and one in the includes.

const check_frutas = ["banana", "uva", "pera"]
const frutas_a = ["banana", "limao", "pera", "goiaba"]
const frutas_b = ["tomate", "tangerina", "pera", "melancia"]
const frutas_c = ["pera", "melancia", "uva", "banana"]

let best_match = []
for(arr of [frutas_a, frutas_b, frutas_c])
{
  let interseccao = check_frutas.filter(x => arr.includes(x))
  console.log(interseccao)
  if(best_match.length < interseccao.length)
    best_match = interseccao  
}

console.log(best_match)

1

Try using a loop and increment accordingly. What do you mean? Let’s create type a "score" system and the array with more "points" is the most similar.

window.onload = function() {
  // Array com o checkbox do usuário
  const check_frutas = ["banana", "uva", "pera"];
  // Arrays pra comparação
  const frutas_a = ["banana", "limao", "pera", "goiaba"];
  const frutas_b = ["tomate", "tangerina", "pera", "melancia"];
  // Reconhece o botão
  var btn = document.getElementById('btn');

  // Função pra fazer a comparação entre dois arrays
  function compararArrays(arrayAComparar, arrayASerComparado) {
    // Variáveis pra contar os "pontos" dos arrays
    var pontos = 0;
    // Loop para verificação
    for (var i = 0; i < arrayASerComparado.length; i++) {
      for (var j = 0; j < arrayAComparar.length; j++) {
        if (arrayASerComparado[i] === arrayAComparar[j]) {
          pontos += 1;
        }
      }
    }
    return pontos;
  }

  // Aqui vou escrever na tela qual é mais parecido quando o usuário clicar no botão
  btn.onclick = function() {
    var pontos1 = compararArrays(frutas_a, check_frutas);
    var pontos2 = compararArrays(frutas_b, check_frutas);
    var resultado;
    // Compara qual é mais parecido
    if (pontos1 > pontos2) {
      resultado = "O array é mais parecido com o array A";
    } else if (pontos1 < pontos2) {
      resultado = "O array é mais parecido com o array B";
    } else {
      resultado = "O array é tão parecido com o array A quanto com o array B";
    }

    // Escreve na tela qual array é mais parecido
    alert(resultado);
  };
};
<button id="btn">Comparar Arrays</button>

NOTE: I used to compare them a method known as Bubble Sort

1

Hello, welcome to Stackoverflow, the method below checks the similarity and returns the element it considers most similar!

function checkSimilar(collection, a, b) {
    var first=0, last=0;

    for (var i in collection) {    

        if (a.indexOf(collection[i]) !== -1) {
            first++;  
        }  
        if (b.indexOf(collection[i]) !== -1) { 
            last++;    
        }
    }   
    if (first == last) {
       //iguais
       return {all:[a, b], first:null, last:null};   
    } else if (first > last) {    
       //a é mais similar
       return {all:null, first:a, last:null};  
    } else {
       //b é mais similar
       return {all:null, first:null, last:b};
    }
} 

var similar = checkSimilar(["banana", "uva", "pera"], ["banana", "limao", "pera", "goiaba"],["tomate", "tangerina", "pera", "melancia"]);

console.log(similar)

Another return option would be to edit the code according to your preference:

 if (first == last) {
    //iguais
    return [a, b];   
 } else if (first > last) {    
    //a é mais similar
    return a;  
 } else {
    //b é mais similar
    return b;
 }

or:

 if (first == last) {
     //iguais
     return  'a e b são semelhantes';   
 } else if (first > last) {    
     //a é mais similar
     return 'a é mais similar';  
 } else {
     //b é mais similar
     return 'b é mais similar';
 }

0

I made this simple algorithm that returns the array containing the most similar content. (There is probably a more performative implementation).

function similarities(arrayCheck, arrayOne, arrayTwo){

    let arrayOneCount = 0;
    let arrayTwoCount = 0;

    for(let i = 0; i < arrayCheck.length; i++){

        if(arrayOne.includes(arrayCheck[0])) arrayOneCount++;
        if(arrayTwo.includes(arrayCheck[0])) arrayTwoCount++;
    }

    if(arrayOneCount > arrayTwoCount)
        return arrayOne;

    if(arrayOneCount < arrayTwoCount)
        return arrayTwo;

    return arrayOne;
}

I recommend doing a more in-depth search before asking the question. There was already a question similar to yours here in the stack itself

0

Follows another form:

const check_frutas = ["banana", "uva", "pera"];
const frutas_a = ["banana", "limao", "pera", "goiaba"];
const frutas_b = ["tomate", "tangerina", "pera", "melancia"];
const frutas_c = ["pera", "melancia", "uva", "banana"];
const lista = [frutas_a, frutas_b, frutas_c];

const retorno = lista.map((x) => x.filter((y) => check_frutas.includes(y)))
                        .reduce((acc,cur,idx) => { cur.length > acc.matchCout && (acc = { matchCout: cur.length, array: lista[idx] }); return acc; }, { matchCout: 0, array: [] });

returns:

{
array: ["pera", "melancia", "uva", "banana"],
matchCout: 3
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.