Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { isArray } from './utils';
export default function flattenArray(arr) {
// Use Array.reduce to get our result
let flattened = arr.reduce(function(current, item) {
// Store a reference to the current item
let temp = item;
// Check if the item is an array
if (isArray(item)) {
// If it is an array, then apply the function again (recursively) and store the result in temp
temp = flattenArray(item);
}
// concat temp with the current result
return current.concat(temp);
}, []);
return flattened;
}
import test from 'ava';
import { isArray } from './utils';
import flattenArray from './flattenArray';
test(t => {
let testPass = [[1,2,[3, [5, 6]]],4];
let testFail = {};
t.true(isArray(testPass));
t.false(isArray(testFail));
});
test(t => {
let test = [[1,2,[3, [5, 6]]],4];
let expected = [ 1, 2, 3, 5, 6, 4 ];
let result = flattenArray(test);
t.same(result, expected);
});
// Check is something is an Array, use Array.isArray if it's supported, otherwise use instanceOf
export function isArray(arr) {
return Array.isArray ? Array.isArray(arr) : arr instanceof Array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment