0

I want to add/remove an element to/from an array depending on an boolean value. This is what is working.

Is it possible to make this a bit shorter?

if (state === true) {
    const index = array.indexOf(id)
    if (index > -1)
        array.splice(index, 1)
}
if (state === false) {
    const index = array.indexOf(id)
    if (index === -1)
        array.push(id)
}

5 Answers 5

1

Shortened & simplified.

const index = array.indexOf(id);

if (state === true && index > -1) {
  array.splice(index, 1)
} else if (state === false && index === -1)  {
  array.push(id)
}

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

Comments

1

A bit shorter:

const index = array.indexOf(id);

if (state === true && index > -1) {
    array.splice(index, 1);
} else if (state === false && index === -1) {
    array.push(id);
}

Comments

1

You could use a conditional (ternary) operator ?: with checking state, depending of the function.

In the first part push only if state is falsy and in the second part splice only if state is truthy.

const index = array.indexOf(id);
index === -1 ? state || array.push(id) : state && array.splice(index, 1);

Table of truth

index  state  index === -1 ? state || array.push(id) : state && array.splice(index, 1)
-----  -----  ------------------------------------------------------------------------
   -1   true        true      true
   -1   false       true      false   array.push(id)
!==-1   true       false                                true    array.splice(index, 1)
!==-1   false      false                               false

Comments

0

Use the following short approach:

const index = array.indexOf(id);
if (typeof state === 'boolean') {  // considering only boolean values for `state`
    (state && index > -1 && array.splice(index, 1)) || (!state && index === -1 && array.push(id));
}

Comments

0
const index = array.indexOf(id);

//condition           ? condition true         : condition false
(state && index > -1) ? array.splice(index, 1) : array.push(id);

This is using a shortened conditional operator
There is a handy list of some JavaScript Shorthands here

5 Comments

no. actually you miss the part where no splice and pushing has to take place.
@NinaScholz that would be this part - : array.push(id);
@NinaScholz can you explain why you think Im missing the push?
you may have a look to my table of truth, there are 4 possibilites and you just have one in the check and leave the three others as one.
@NinaScholz Fair enough, I misunderstood your original comment, ironically you should have written or instead of and.

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.