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

132
Views
Push item onto array on condition in one line

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...)

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

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);
about 4 years ago · Santiago Trujillo 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!