Skip to content

Instantly share code, notes, and snippets.

@kdubbels
Last active August 19, 2020 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdubbels/6ff95dad73d89a6b90ad62d98a09550c to your computer and use it in GitHub Desktop.
Save kdubbels/6ff95dad73d89a6b90ad62d98a09550c to your computer and use it in GitHub Desktop.
Use the reduce method in combination with the concat method to “flatten” an array of arrays into a single array that has all the elements of the original arrays.
// Use the reduce method in combination with the concat method to
// “flatten” an array of arrays into a single array that has all
// the elements of the original arrays.
// My original "solution":
let arrays = [[1, 2, 3], [4, 5], [6]];
arrays.reduce((accumulator, currentValue) => accumulator.concat(currentValue),[]); // [1, 2, 3, 4, 5, 6]
// This solution works on the sole test case in Chapter 5 of Eloquent JavaScript; but it doesn't work with nested arrays.
// For instance:
// [[1], [1,[1,2]], [3,[4,[5,6]]]].reduce((accumulator, currentValue) => accumulator.concat(currentValue),[]);
// will return:
// [1, 1,[1, 2], 3, [4,[5, 6]] 🙁
// Jem Young provides this alternate solution in in FrontEndMasters course. The solution above works with the caveat
// that it cannot handle nested arrays - it will work on an array of arrays that only contain primitives (or arrays of
// primitives and arrays that only contain primitives) . It will not work on arrays of arrays of arrays. Introducing
// recursive concatenation resolves this problem by flattening the nested arrays.
function flatten(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
acc = acc.concat(flatten(item));
} else {
acc.push(item);
}
return acc;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment