Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flattening an array? [].concat(...[array])?

I understand that [].concat(...array) will flatten an array of arrays, but I've been taking a webpack course, and in the code to load presets it uses the syntax [].concat(...[array])

My understanding of it is:

const array = [[1,2,3], [4,5,6], [7,8,9]];
const result = [].concat(...array);       // [1,2,3,4,5,6,7,8,9]
const result2 = [].concat(...[array]);    // [[1,2,3], [4,5,6], [7,8,9]]

It's definitely confusing me because the course code (below) does work, but I can't see what [].concat(...[array]) achieves?

const webpackMerge = require("webpack-merge");

const applyPresets = (env = {presets: []}) => {
  const presets = env.presets || [];
  /** @type {string[]} */
  const mergedPresets = [].concat(...[presets]);
  const mergedConfigs = mergedPresets.map(presetName =>
    require(`./presets/webpack.${presetName}`)(env)
  );

  return webpackMerge({}, ...mergedConfigs);
};

module.exports = applyPresets;

Can anyone give me a vague idea please?

like image 945
NickW Avatar asked Oct 16 '22 04:10

NickW


1 Answers

This is a bit odd.

the concat() method takes each element from multiple arrays and adds them to a new array. So

[].concat([1],[2],[3]) = [1, 2, 3]

Now the [somevariable] syntax, places the somevariable into an array.

let arr1 = [1, 2, 3, 4]
let arr2 = [arr1]
console.log(arr2) // prints [[1, 2, 3]]

And finally, the ... syntax (called spread syntax) essentially disassembles an array, so its elements can be accessed directly

function myFunc(...[x, y, z]) {
  return x * y* z; // without the dots, we'd have to say arr[0] * arr[1] * arr[2]
}

Thus, the [].concat(...[array]) expression you're confused about indeed accomplishes nothing; it places array into another array with the [] syntax, then immediately disassembles it back to how it was with the ... syntax. An equivalent expression is [].concat(array), which doesn't accomplish much since it has a single argument and the contact() method is called on an empty array.

like image 112
McKay M Avatar answered Oct 21 '22 04:10

McKay M