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]
if? You could use&&but it's not very readable if you do that imo.? :operator forms an expression, not a statement, and in JS (and most languages) all expressions have to evaluate to some value (unless you want to ruin everything withthrow, I guess...)reduceinstead offilterandmap?.filter()(as suggested in the below answer). The&&solution doesn't sit inside of the.push(), it would be<condition> && arr.push(...), but it's not recommended to write code like that as you're writing an expression that isn't being used for it's result but rather just its side effects (more details). It still isn't clear why you want to remove theifthough. While&&works you should avoid it for side-effect code and instead favour anifstatement