Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda