0

Following is the answer I am looking at - https://stackoverflow.com/a/45225396/639406

Code -

var result = [].concat.apply([], strs1.map(function(str1) {
  return strs2.map(function(str2) {
    return str1 + '-' + str2;
  });
}));

Most of the thing is clear to me except the use of apply here. Please let me know what this method is doing here and the first [] parameter to the apply method.

I gone though this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply but it looks too complicated.

Nesh
  • 2,389
  • 7
  • 33
  • 54
  • 1
    Have you read [How does .apply(Math, arrayName) work? (javascript)](https://stackoverflow.com/q/24541600/218196) ? – Felix Kling Jul 20 '17 at 22:09
  • The MDN link you provided describes it in enough detail. Any function can be invoked with `call()` or `apply()`. This example returns a single flattened array; if it had been `[].concat(strs1.map...)` it would have returned an array of three other arrays (one for each `strs1` value). – Cᴏʀʏ Jul 20 '17 at 22:09
  • FWIW, in ES6 you could write `[].concat(...strs1.map(str1 => strs2.map(str2 => \`${str1}-${str2}\`)));` instead – Felix Kling Jul 20 '17 at 22:11
  • @FelixKling Thx I will go through the first link – Nesh Jul 20 '17 at 22:12
  • 1
    "*But it looks too complicated*" - what parts do you not understand about the explanation specifically? – Bergi Jul 20 '17 at 22:28
  • Does this answer your question? [What exactly is concat + apply doing to flatten an array?](https://stackoverflow.com/questions/54351817/what-exactly-is-concat-apply-doing-to-flatten-an-array) – SuperStormer Oct 09 '22 at 09:55

0 Answers0