Home > Enterprise >  How Can I Use Ternary Conditional Operator Without Else?
How Can I Use Ternary Conditional Operator Without Else?

Time:09-23

I got a code block like this

const numbers = [1, 2, 3, 4, 5, 6];

const newNumbers = numbers.reduce((acc, num) => {
  acc.push(num > 3 ? num : null);
  return acc;
}, []);
console.log('new Numbers', newNumbers);
//returns new Numbers,[null, null, null, 4, 5, 6]

But I don't want null values to be pushed in array. I want to perform the action like this but without if:

const newNumbers = numbers.reduce((acc, num) => {
  if (num > 3) {
    acc.push(num);
  }  
  return acc;
}, []);
console.log(newNumbers);
//returns new Numbers,[4, 5, 6]

CodePudding user response:

How Can I Use Ternary Conditional Operator Without Else?

No. The conditional operator always has to "return" a value. Imagine it was possible to leave out the alternative (e.g. arr.push(num > 3 ? num)), what value would be pushed to the array?

In this specific case there is a better tool for the job: Array#filter:

const newNumbers = numbers.filter(num => num > 3)

CodePudding user response:

Use && instead of ?,

const numbers = [1, 2, 3, 4, 5, 6];

const newNumbers = numbers.reduce((acc, num) => {
  num > 3 && acc.push(num)
  return acc;
}, []);
console.log(newNumbers);

//returns new Numbers,[4, 5, 6]

CodePudding user response:

You can always do:

num > 3 ? acc.push(num) : {}
  • Related