1

I want to do this...

var all = [];
_.each(leftArr, (leftItem) => { 
   all.concat(leftItem.concat(getSomeOtherArray());
})
return all;

But I want to do it in a clean functional way. How can I do it without opening the foreach loop?

Exitos
  • 29,230
  • 38
  • 123
  • 178
  • 3
    Provide your array and expected result. – kind user Nov 09 '17 at 20:18
  • What's `leftArr`? What about `getSomeOtherArray()`? Why are you calling `getSomeOtherArray()` for each element in `leftArr`? – gen_Eric Nov 09 '17 at 20:19
  • Also `.concat()` returns a new array, so your `all` array is not getting filled with anything. – gen_Eric Nov 09 '17 at 20:20
  • 2
    Possible duplicate of [What is the most efficient way to concatenate N arrays in JavaScript?](https://stackoverflow.com/questions/5080028/what-is-the-most-efficient-way-to-concatenate-n-arrays-in-javascript) – iPhoenix Nov 09 '17 at 20:21
  • Also, how is this not "clean?" What do you mean by "functional?" – gen_Eric Nov 09 '17 at 20:23

1 Answers1

1

Use Array#map to concat the leftItem with the results of getSomeOtherArray(), then flatten everything by spreading into another concat:

const leftArr = [[1], [2], [3]];

const getSomeOtherArray = () => ['a'];

const all = [].concat(...leftArr.map((leftItem) => leftItem.concat(getSomeOtherArray())));

console.log(all);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209