I want to create a JavaScript array using a literal containing the elements. I only want a chunk of those elements (somewhere in the middle of the array) to be included if a certain expression is true. I can obviously create the array with the always-present elements only then programmatically insert the additional elements at the appropriate index if the condition is true, but I don't want to do that because the non-ES6 ways of doing it are not very pretty and you have to mentally think about indexes to understand where the conditional elements are going to go if the condition is true (not very readable). Here is a simplified example of what I know how to do (but dislike) versus what I'd like to do (but don't know how). In the last example, instead of undefined
at the index, I simply don't want an element there. Is there a way to achieve this with a literal and expressions, or will I have to end up doing some array manipulation to achieve this?
function createArrayTheWayIDislike(condition) {
var array = [
'a',
'd'
];
if(condition) {
array.splice.apply(array, [1, 0].concat(['b', 'c']));
}
console.log(array);
}
function createArrayTheWayIWantTo(condition) {
var array = [
'a',
condition ? 'b' : undefined,
condition ? 'c' : undefined,
'd'
];
console.log(array);
}
createArrayTheWayIDislike(true);
createArrayTheWayIDislike(false);
createArrayTheWayIWantTo(true);
createArrayTheWayIWantTo(false);
You can filter the results before returning the array
function createArrayTheWayIWantTo(condition) {
var array = [
'a',
condition ? 'b' : undefined,
condition ? 'c' : undefined,
'd'
].filter(e => e);
console.log(array);
}
createArrayTheWayIWantTo(true);
createArrayTheWayIWantTo(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With