Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!