0

I have input like this:

const a = 'lol',
      b = ['1','2','3'],
      c = 'c';

I want to merge it so the output would be this array:

['lol', '1', '2', '3', 'c']

I tried with spread operator like this

const arr = [...a, ...b, ...c]
console.log(arr)

but it consoles

["l", "o", "l", "1", "2", 3, "c"]

2
  • 2
    ...a will spread the string into the individual characters. Just omit the spread and have [a, ...b, c] Commented Jan 1, 2020 at 23:58
  • b.unshift(a); b.push(c); Commented Jan 2, 2020 at 0:21

2 Answers 2

5

Only use spread if it's an array:

const arr = [a, ...b, c];

More dynamically, with .flat:

const a = 'lol',
      b = ['1','2','3'],
      c = 'c';
const arr = [a, b, c].flat();
console.log(arr);

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

5 Comments

But the input can be more strings and arrays
@dopeCode then...just do the same - spread the arrays, don't spread the strings. What's the problem with that?
@dopeCode Put all items of the input into the array, then flatten that array - see the snippet.
.flat() won't work on Edge or IE. Just a comment.
@StackSlave neither would the spread operator, however if OP is using it, then IE doesn't seem to be a concern.
-2

A better way to get each element in a function.

const a = 'lol', b = ['1','2','3'], c = 'c';

const _join = (...params) => { return Array.prototype.concat.apply([],params) }

const result = _join(a,b,c)

console.log(result)

1 Comment

This currently fails and prints Array(9) ["l", "o", "l", "1", ",", "2", ",", "3", …]

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.