If statement inside array javascript

Add elements conditionally

/**
 * Add item to array conditionally.
 * @param {boolean} condition
 * @param {*} value new item or array of new items
 * @param {boolean} multiple use value as array of new items (for future)
 * @returns {array} array to spread
 * @example [ ...arrayAddConditionally(true, 'foo'), ...arrayAddConditionally(false, 'bar'), ...arrayAddConditionally(true, [1, 2, 3]), ...arrayAddConditionally(true, [4, 5, 6], true) ] // ['foo', [1, 2, 3], 4, 5, 6]
 */
export const arrayAddConditionally = (condition, value, multiple) => (
    condition
        ? multiple ? value : [value]
        : []
);

Create array with conditional elements


/**
 * Create array with conditional elements
 * @typedef {[condition: boolean, value: any, multiple: boolean]} ConditionalElement
 * @param {(ConditionalElement|*)[]} map non-array element will be added as it is, array element must allways be conditional
 * @returns {array} new array
 * @example createArrayConditionally([[true, 'foo'], [false, 'baz'], [true, [1, 2, 3]], [true, [4, 5, 6], true], {}]) // ['foo', [1,2,3], 4, 5, 6, {}]
 */
export const createArrayConditionally = (map) => (
    map.reduce((newArray, item) => {
        // add non-conditional as it is
        if (!Array.isArray(item)) {
            newArray.push(item);
        } else {
            const [condition, value, multiple] = item;
            // if multiple use value as array of new items
            if (condition) newArray.push[multiple ? 'apply' : 'call'](newArray, value);
        }
        return newArray;
    }, [])
);

This blog post shows how you can conditionally add elements inside Array literals and properties inside object literals.

Conditionally adding elements inside Array literals  

The following code shows how a boolean cond determines whether or not the element 'a' is added to the Array arr.

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

This trick works, because the spread operator (...) for Array literals does nothing if its operand is an empty Array:

> [...[], 'a']
[ 'a' ]

Conditionally adding properties inside object literals  

You can use the proposed spread operator for properties in the same manner. Again, a boolean cond determines whether the property a is added to the object obj:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

The spread operator for object literals does nothing if its operand is an object without enumerable own properties:

> {...{}, a: 1}
{ a: 1 }

Is it worth it?  

Using the spread operator in this manner leads to slightly cryptic code. Here it is again, for ease of reference:

const arr = [
  ...(cond ? ['a'] : []),
  'b',
];

The crypticity can be worth it if you want to create the Array with a single expression.

Different approaches  

Less cryptic would be to create the Array with the unconditional elements first and to then conditionally insert elements, via slice(). But that leads to error-prone code, because you have to manage indices properly (insert the last one of multiple elements first, etc.).

An elegant and self-descriptive solution is to use push() to construct the Array:

const arr = [];
if (cond) {
    arr.push('a');
}
arr.push('b');

Variations of the original approach  

A variation of the original approach is to use spread and a helper function:

const arr = [
  ...insertIf(cond, 'a'),
  'b',
];
function insertIf(condition, ...elements) { // (A)
    return condition ? elements : [];
}

In line A, the triple dots are the rest operator which collects the remaining arguments in an Array and assigns it to elements.

Another alternative is to conditionally insert either elements or undefineds and to then filter the latter values out:

const arr = [
  (cond ? 'a' : undefined),
  'b',
].filter(x => x !== undefined);

Further reading  

  • Sect. “The spread operator (...)” in “Exploring ES6”
  • ES proposal: Rest/Spread Properties
  • Sect. “Rest parameters” in “Exploring ES6”

How do you add a condition to an array?

Its pretty simple. Create array with essential elements. Then add conditional elements to the array. Now add other elements if required.

Can we use array in if condition?

In other words, it fully supports Intelligent Arrays. For example, if condition «a» is an array of Booleans (true or false values), it returns an array with the same index, containing «b» or «c» as appropriate: Variable X := -2 ..

How do you do an if statement with arrays?

If that array is at that first state of [1], and "one". equals(match) then it sets the array to arrayCount[2] and then from there on. Basically, if "one" = match, it should set arrayCount to 2, if "two" = match AND the first if statement has already been executed, it will play the test sound.

How do you find if an element exists in an array in JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.