Search code examples
javascriptarrayslodash

Lodash union won't work with the spread operator


I am using lodash and it's union function. But when I use a spread operator within union I am no longer getting the normal, expected result. What am I doing wrong and why won't lodash work with the spread operator? Thanks!

x = [1, 2, 3, 4]

y = [3, 5]

normalResult = _.union(x, y)
unexpectedResult = _.union(...x, y)

// normalResult = [1, 2, 3, 4, 5]
// unexpectedResult = [3, 5]

Solution

  • _.union expects each argument to be an array. When you use ...x you're spreading the array into separate arguments, which is not what it wants.

    The spread operator would be useful if you had a 2-dimensional array and you wanted to merge each of the contained arrays with _.union, e.g.

    x = [1, 2, 3, 4]
    y = [3, 5]
    a = [x, y];
    result = _.union(...a);