Last active
June 7, 2016 16:28
-
-
Save heroqu/2b56532791a84c49790edc33a8e10952 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict' | |
| /** | |
| * flatten an array of arbitrarily nested arrays of integers into a flat array of integers | |
| */ | |
| function flat_numeric_arr(x, res) { | |
| res = res || []; | |
| if (typeof x === 'number') { | |
| res.push(x); | |
| } else if (Array.isArray(x)) { | |
| x.forEach((y) => { | |
| flat_numeric_arr(y, res); | |
| }) | |
| } else { | |
| // throw 'improper argument type'; // ok, just ignore for now | |
| } | |
| return res; | |
| } | |
| // let a = [1,2,[3, 4], 'w', 5,[[6,7,8], 9, 10]]; | |
| // let b = flat_numeric_arr(a); | |
| // console.log(b); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment