Home > database >  Push item onto array on condition in one line
Push item onto array on condition in one line

Time:07-24

I want something like this and I would like to know if this is possible in JavaScript in one line, or I have to write an if statement

// these versions adds fasle to the array if condition = false
let arr = await getArray(params).push(condition && itemToAdd);
arr = await getArray(params).push((() => condition && itemToAdd)());

// this version adds undefined to the array if condition = false
arr = await getArray(params).push((() => { if (condition) return itemToAdd })());

(the reason I included the getArray part is cuz that's how it looks in my code and I don't actually save this array to a var arr only its being returned right away to its calling function, so that's why I don't want to add a line for the if statement...)

CodePudding user response:

Not sure why you want to do it in a single line, but this can work

let arr = [...await getArray(), itemToAdd].slice(0, condition ? undefined : -1);

Here we are pushing the itemToAdd in the array regardless of the condition, but we remove the last element (itemToAdd) if the condition is false.

CodePudding user response:

if you are working with reactjs then you can use useState for conditions

const [isCondition, setisCondition] = useState(false);

//but you need if/else to change useState

if(this_happens) {

setisCondition(true) } else { setisCondition(false) }

//you can do it as like

let arr = await getArray(params).push(isCondition && itemToAdd);
  • Related