Search code examples
javascriptarraysfunctionfunctional-programming

List self nesting in Javascript


Question

I am trying to achieve a function that transforms a list into a second list with two sublist of itself. This function must do so by being called in a chain

i.e


[1,2,3] => [[1,2,3],[1,2,3]]

The function form should look something like this, where fn is the function i am looking for


[1,2,3].map(x=>[x]).fn() //  => [[[1],[2],[3]],[[1],[2],[3]]]


Solution

  • Solution

    As suggested in the comments below

    [1,2,3,4].reduce(([l, r], x) => [[...l, x], [...r, x]], [[], []]) // => [[1,2,3,4],[1,2,3,4]]