how to compare whether a dataset of an array contains in the other javascript array

Asked

Viewed 107 times

0

How do I compare whether a dataset of an array contains in the other javascript array?

Array 1

//Combinações possíveis para acertar a carta
const equals = [
    ['imgCard_0', 'imgCard_6'],
    ['imgCard_1', 'imgCard_7'],
    ['imgCard_2', 'imgCard_8'],
    ['imgCard_3', 'imgCard_9'],
    ['imgCard_4', 'imgCard_10'],
    ['imgCard_5', 'imgCard_11'],
]

Array 2 named rotateCards created dynamically as the user clicks on the chart

["imgCard_0", "imgCard_9"]

I need to check if the two cards clicked by it are in the possible combinations of array 1

tried to do with index, but always returns -1, ie not found.

tried also so const Equal = ! rotateCards.some((val, idx) => val !== equals[idx]), and also unsuccessful so far

I also tried this way without success

for (i = 0; i < equals.length; i++) {
        if (clickCard.indexOf(equals[i]) >= 0) {
            console.log(equals[i]);
        }
    }

Image that demonstrates that even though the combination is correct it returns false. inserir a descrição da imagem aqui

  • I’ve tried it this way, I don’t know why it always returns false regardless of comparison

3 answers

2

If you want to find the index of an element within an array use the method Array.prototype.findIndex() which returns the index of the first element in the array that satisfies the given test function, otherwise returns -1 indicating that no element passed the test.

const equals = [
  ['imgCard_0', 'imgCard_6'],
  ['imgCard_1', 'imgCard_7'],
  ['imgCard_2', 'imgCard_8'],
  ['imgCard_3', 'imgCard_9'],
  ['imgCard_4', 'imgCard_10'],
  ['imgCard_5', 'imgCard_11'],
];

//Cartas selecionadas pelo usuário. 
//Como não foi informado se o sistema ordena dinamicamente os dados usei uma sequência válida porém em ordem invertida como exemplo.
let rotateCards = ["imgCard_10", "imgCard_4"];

//Localiza o índice de rotateCards em equals fazendo a comparação direta dos elementos correspondente 
//e também a comparação dos elementos em ordem invertida.
let idx = equals.findIndex((e) =>
     (e[0] == rotateCards[0] && e[1] == rotateCards[1]) 
  || (e[0] == rotateCards[1] && e[1] == rotateCards[0]) //Se a comparação em ordem invertida for desnecessária comente essa linha.
);

console.log(idx);

0

Unfortunately javascript cannot compare arrays. So ['oi'] == ['oi'] will return false.

To make it work, you have to compare them as if they were strings.

In your case, use a JSON stringify and a simple Array. that’s enough!

// variável, só por didática
const selectedCard = ['imgCard_0', 'imgCard_6'];

const isEqual = equals.some(combination => {
    return JSON.stringify(combination) == JSON.stringify(selectedCard)
})

if (isEqual) { /* acertou a combinação! */ }

-1

In function checkCombination the function is used Every, so we can validate regardless of the order of choice of your deck and the number of combinations.

const equals = [
    ['imgCard_0', 'imgCard_6'],
    ['imgCard_1', 'imgCard_7'],
    ['imgCard_2', 'imgCard_8'],
    ['imgCard_3', 'imgCard_9'],
    ['imgCard_4', 'imgCard_10'],
    ['imgCard_5', 'imgCard_11'],
    ['imgCard_5', 'imgCard_11', 'imgCard_7'],
]

function checkCombination(deck, combinations) {
    for(let a = 0; a < combinations.length; a++) {
        if(deck.length != combinations[a].length) continue
        const exists = deck.every((card) => combinations[a].indexOf(card) > -1)
        if(exists) return true
    }

    return false
}

checkCombination(['imgCard_5', 'imgCard_11', 'imgCard_7'], equals); //true
checkCombination(['imgCard_1', 'imgCard_5'], equals); //false
checkCombination(['imgCard_11', 'imgCard_5', 'imgCard_7'], equals); //true
checkCombination(['imgCard_0', 'imgCard_2', 'imgCard_7'], equals); //false

Browser other questions tagged

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