Reputation: 17332
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)
}
Upvotes: 0
Views: 399
Reputation: 386604
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
Upvotes: 1
Reputation: 6332
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
Upvotes: 0
Reputation: 92854
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));
}
Upvotes: 0
Reputation: 41893
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)
}
Upvotes: 1
Reputation: 18279
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);
}
Upvotes: 1