Skip to content

Instantly share code, notes, and snippets.

@tinkertrain
Last active March 25, 2016 19:40
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 tinkertrain/f8a746a8a08ac0b1e70e to your computer and use it in GitHub Desktop.
Save tinkertrain/f8a746a8a08ac0b1e70e to your computer and use it in GitHub Desktop.
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