4

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

2
  • the rest operator doesn't work well?, for example if you want to insert starting at arr[1], arr[3] = ..myArr Commented May 10, 2018 at 20:09
  • @afcosta Still would be dealing with indexes more than I prefer Commented May 10, 2018 at 20:19

3 Answers 3

8

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

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

2 Comments

So just filtering out the undefined elements after defining the array. Pretty much what I want while maintaining readability.
You may want to use e => e !== undefined for the filter, depending on what your array contains. Using the identity function will remove all falsy elements from the array.
3

How about using array destructuring, with a ternary operator to do this? Here's an example:

// Replace with your real conditions
const condition1 = true;
const condition2 = false; 

const array = [
  'a',
  ...condition1
    ? ['b']
    : [],
  ...condition2
    ? ['c']
    : [],
  'd'
];

// Should log ['a', 'b', 'd'];
console.log(array);

1 Comment

While this works and I appreciate the answer, I am trying to avoid ES6 features like destructuring in my app (for browser compatibility).
0

Personally I use this syntax which I quite like:

const arr = Array.skipUndef(
 'a',
 condition ? 'b' : undefined,
 condition ? 'c' : undefined,
 'd'
)

Under the hood it's the same as [...].filter((arg) => arg) but with some minor syntactic sugar (I personally don't like the option with the filter line, especially when the array is long and you have multiple levels of indent and it's just kind of dangling there somewhere at the end).

In order to do this, just write the following file somewhere and import it into your index.ts:

declare global {
  interface ArrayConstructor {
    skipUndef<T>(...args: (T | undefined)[]): T[];
  }
}

Array.skipUndef = function <T>(...args: (T | undefined)[]) {
  return args.filter((arg) => arg !== undefined) as T[];
};

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.