Skip to content

Instantly share code, notes, and snippets.

@fczuardi
Created December 8, 2016 17:00
Show Gist options
  • Select an option

  • Save fczuardi/ecf4c18f0424d517425cdce69bc0cc3d to your computer and use it in GitHub Desktop.

Select an option

Save fczuardi/ecf4c18f0424d517425cdce69bc0cc3d to your computer and use it in GitHub Desktop.
interview question: implement array flatten
// unwraps one level by accumulating the
// array concatenation of one item with the next item
const unwrap = arr => arr.reduce((acc, item) => acc.concat(item), []);
// flattens an array with nested array items
const flatten = arr => {
const needsUnwrapping = arr.filter( i => Array.isArray(i)).length > 0;
if (!needsUnwrapping) {
return arr;
}
return flatten(unwrap(arr));
};
// ------
//tests
const a = [[1], [2], [3], [4]];
const b = [1, [2], [[3, [4]]]];
const c = [[1, 2, [3]], 4];
const answer = [1, 2, 3, 4];
const isCorrect = arr => JSON.stringify(arr) === JSON.stringify(answer);
console.log(isCorrect(flatten(a)));
console.log(isCorrect(flatten(b)));
console.log(isCorrect(flatten(c)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment