admin管理员组

文章数量:1406951

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

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

Share asked May 10, 2018 at 20:05 JellyRaptorJellyRaptor 7551 gold badge8 silver badges20 bronze badges 2
  • the rest operator doesn't work well?, for example if you want to insert starting at arr[1], arr[3] = ..myArr – af costa Commented May 10, 2018 at 20:09
  • @afcosta Still would be dealing with indexes more than I prefer – JellyRaptor Commented May 10, 2018 at 20:19
Add a ment  | 

3 Answers 3

Reset to default 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);

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

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[];
};

本文标签: Define JavaScript array literal with conditional elementsStack Overflow