Reputation: 930
I am trying to concat (with uniques values) two arrays and if the second array sometimes is a string.
Maybe it have a bug, but these are my three tryings:
let a = 'abcdefg'
// First try
[...new Set([...[], ...(typeof(a) == 'string'? [a]: a))]
// Second try
[...new Set([...[], [(typeof(a) == 'string'? ...[a]: ...a)]]
// Third try
[...new Set([...[], (typeof(a) == 'string'? ...[a]: ...a)]
Upvotes: 2
Views: 1995
Reputation: 12544
If I understand correctly, if the a
parameter is a string, and not a collection, searching unique values and the need for a Set is moot. Then you could short circuit as typeof a === 'string' ? [a] : [...new Set(a)]
let a = 'abcdefg'
const createArr = a => typeof a === 'string' ? [a] : [...new Set(a)];
console.log(createArr(a));
console.log(createArr([a,a,'aa']));
Upvotes: 0
Reputation: 386728
Instead of
[...new Set([...[], ...(typeof a === 'string' ? [a] : a))]
take, watch the round, square, round and squere closing brackets at the end.
[...new Set([...[], ...(typeof a === 'string' ? [a] : a)])]
// ^
let a = 'abcdefg'
console.log([...new Set([...[], ...(typeof a === 'string' ? [a] : a)])]);
Upvotes: 4
Reputation: 192422
Instead of using spread, you can use Array.concat()
, because it treats combine arrays and values in the same way:
const a = 'abcdefg'
console.log([...new Set([].concat([], a))])
console.log([...new Set([].concat([], [a]))])
Upvotes: 2