Home > Software engineering >  Pushing in an array if the condition is true
Pushing in an array if the condition is true

Time:04-26

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

Thank you so much :) ! It works !!!

  • Related