0

I have variables assigned to values as:

let x = 5;
let y = 17;
let z = 0;

const newArr = [];

Here I am trying to push the x, y, x values if they aren't falsy values

I am doing as:

if(x){
  newArr.push(x);
}
if(y){
  newArr.push(y);
}
if(z){
  newArr.push(z);
}

May I know more efficient way to do this, TIA

1 Answer 1

4

You might put all the variables into another array, then filter that array:

let x = 5;
let y = 17;
let z = 0;
const newArr = [x, y, z].filter(Boolean);
console.log(newArr);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.