Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
How to make dynamic variable to check array with .every

For a project we need to check if all numbers in a card, match another card with drawn numbers. When hardcoded with a const checkCard = card001 it goes well with .every. When trying to choose the card a dynamic way, pulling the number from a localStorage (e.g. const card = 'card'+cardNumber), an error pops up with t.every is not a function. The question: how to make this dynamic. We hope someone is able to help to overcome this issue.

checkCard = () => {
    var cardNumber = localStorage.cardNumber;
   
    const card001 = [14, 4, 10, 8, 12, 30, 28, 23, 16, 27, 41, 35, 43, 39, 53, 57, 46, 48, 56, 74, 68, 75, 70, 66]
    const card002 = [15, 13, 8, 1, 12, 26, 20, 19, 28, 24, 38, 42, 33, 41, 59, 53, 60, 55, 51, 68, 62, 71, 70, 65]
    const card003 = [11, 5, 4, 13, 9, 23, 27, 16, 18, 26, 44, 38, 40, 36, 53, 47, 56, 55, 50, 69, 65, 63, 61, 74]

    const previousCallList = JSON.parse(JSON.stringify(this.previousCallList));
    console.log('previousCallList: ', previousCallList)
    const previousCallListNumber =  JSON.parse(JSON.stringify(this.previousCallListNumber));
    console.log('previousCallListNumber: ', previousCallListNumber)

    //const card = 'card'+cardNumber;
    const checkCard = card001

    const checkDrawn = previousCallListNumber ;
    const containsAll = checkCard .every(element => {
      return checkDrawn.includes(element);
    });
    console.log(containsAll); // 👉️ true

    }
  }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There's a difference between these two lines:

// Point `checkCard` to the current array stored in `card001`
const checkCard = card001

// Point `checkCard` to a string "card001"
const checkCard = "card001"

When you write 'card'+cardNumber, you're creating a new string, not a reference to another variable.

If you want to dynamically pick a variable based on its name, you can define named properties on an object. For example:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};


console.log(
  myObject["a"],
  myObject["b"],
  myObject["c"]
)

Or, with your data:

const cardNumber = "001";
   
const card001 = [14, 4, 10, 8, 12, 30, 28, 23, 16, 27, 41, 35, 43, 39, 53, 57, 46, 48, 56, 74, 68, 75, 70, 66]
const card002 = [15, 13, 8, 1, 12, 26, 20, 19, 28, 24, 38, 42, 33, 41, 59, 53, 60, 55, 51, 68, 62, 71, 70, 65]
const card003 = [11, 5, 4, 13, 9, 23, 27, 16, 18, 26, 44, 38, 40, 36, 53, 47, 56, 55, 50, 69, 65, 63, 61, 74]

const cardVarName = "card" + cardNumber;
log(cardVarName); // This is now the string "card001", not a reference to the card001 variable


// Store the cards in an object
const cards = { card001, card002, card003 };
// Reference a card using obj[propertyName]
log(cards[cardVarName])


function log(x) { console.log(JSON.stringify(x)); }

about 4 years ago · Juan Pablo Isaza Relatório

0

If you intend to use localStorage you need to familiarize yourself with the syntax, what you have now...

localStorage.cardNumber;

...should've given you an error. The following are two functions that get and set data to and from localStorage:

/*
>key< is a string assigned as an id to stored data.
If there isn't anything stored an empty array is returned/
*/
const getLS = key => JSON.parse(localStorage.getItem(key)) || [];
/*
>key< is same as above. >data< is the value that needs to 
be stored.
*/
const setLS = (key, data) => localStorage.setItem(key, JSON.stringify(data));

Note that LS only stores strings which is why JSON.parse() and JSON.stringify() are used on the data. In the example the lines concerning LS are commented out because SO snippets prohibit them -- just uncomment them when you test them in a normal environment.

Details are commented in example below

// Utility function
const log = data => console.log(JSON.stringify(data));

//const getLS = key => JSON.parse(localStorage.getItem(key)) || [];

//const setLS = (key, data) => localStorage.setItem(key, JSON.stringify(data));

/*
All arrays as parameters so function can be reusable
*/
const deckA = [14, 4, 10, 8, 12, 30, 28, 23, 16, 27, 41, 35, 43, 39, 53, 57, 46, 48, 56, 74, 68, 75, 70, 66];
const deckB = [15, 13, 8, 1, 12, 26, 20, 19, 28, 24, 38, 42, 33, 41, 59, 53, 60, 55, 51, 68, 62, 71, 70, 65];
const deckC = [11, 5, 4, 13, 9, 23, 27, 16, 18, 26, 44, 38, 40, 36, 53, 47, 56, 55, 50, 69, 65, 63, 61, 74];

/**
 * find match between a given number and a
 * number from one or more given arrays
 * @param {number} card = Number to find
 * @param {arrays} cards = One or more arrays
 * @returns {array<object>} Each object is
 *  created like this:
 *  {card: 55, row: 2, col: 17}
 *  "card 55 is in the 3rd array index 17"
 */
const findMatch = (card, ...cards) => {
  //const data = getLS('cards');
  //data.push(card);
  //setLS('cards', data);
  
  // Gather ...cards into an array:
  // [ [deckA], [deckB], [deckC] ]
  const decks = [...cards];
  /*
  First, .map() runs through each sub-array and
  .flatMap() compares each number of each sub-
  array vs. card. If there's a match, return
  a new object (see above) otherwise an empty
  array is returned
  */
  return decks.map((sub, row) => sub.flatMap((num, col) => num === card ? {card: card, row: row, col: col} : [])).flat();
};

log(findMatch(55, deckA, deckB, deckC));
log(findMatch(3, deckA, deckB, deckC));
log(findMatch(25, deckA, deckB, deckC));
log(findMatch(13, deckA, deckB, deckC));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda