Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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)));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement