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

146
Visualizações
Pushing in an array if the condition is true

I have the following chart:

const array = [
  ["one", true],
  ["two", false],
  ["three", false],
  ["four", true]
]

I would like to see this variable added when the value is true:

const add = ["ok"]

So that in the end it looks like this:

[
  [ 'one', true, 'ok' ],
  [ 'two', false ],
  [ 'three', false ],
  [ 'four', true, 'ok' ],
]

Currently, I'm trying the .map method:

const testBoolean = array.map(el => {
  if (el[1] === true){
    array.push(add)
  }
})

console.log(array)

But I don't know where to tell it to push to line 3...

Thanks for your help, and have a nice day :) !

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

0

Never use map if you mean forEach. Only use map if you need the resulting array - in this case testBoolean would be a map

You want this

const array = [
  ["one", true],
  ["two", false],
  ["three", false],
  ["four", true]
]
const add = ["ok"]

array.forEach(el => {
  if (el[1] === true) {  // or just if (el[1]) if you are sure it is always a boolean
    el.push(...add) // or add[0]
  }
})

console.log(array)

about 4 years ago · Juan Pablo Isaza Relatório

0

simply loop through array using forEach and check if the first index is true. For boolean values you don't need to compare it with true or false.

const array = [
  ["one", true],
  ["two", false],
  ["three", false],
  ["four", true]
];

const add = ["ok"]

array.forEach(item => {
    if(item[1]){
    item.push(...add);
  }
});

console.log(array)

documentation for forEach

about 4 years ago · Juan Pablo Isaza Relatório

0

Another way:

const array = [
  ["one", true],
  ["two", false],
  ["three", false],
  ["four", true]
];

const add = ["ok"];


for (const item of array) {
  item[1] && item.push(add[0]);
}

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