'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 :) !



Solution 1:[1]

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)

Solution 2:[2]

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

Solution 3:[3]

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]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mplungjan
Solution 2 ahsan
Solution 3 Eshragh Developer