Skip to content

Instantly share code, notes, and snippets.

@paneru-rajan
Created June 26, 2018 19:08
Show Gist options
  • Save paneru-rajan/0a0d10ed8c0430cb33188efacf74df77 to your computer and use it in GitHub Desktop.
Save paneru-rajan/0a0d10ed8c0430cb33188efacf74df77 to your computer and use it in GitHub Desktop.
Nested arrays of integers into a flat array

Nested arrays of integers into a flat array

For simplicity i have used JS, and i am fully aware that flatArray() will give array of string, insted a array of numbers. Since js is loosely typed, it's okay to save like this. You can use flatIntigerArray() to get array as Integer array, i am supposing that i will receive intger nested array as said.

How to run this:

  1. Please open browser (I am using Chrome)
  2. Press CTRL+SHIFT+J
  3. Paste below code to see output

Javascript Function

function flatArray(array){
    return JSON.stringify(array).replace(/[\[\]]/g,'').split(",");
}

Just call the function with appropriate paramater

nestedArray = [[1,2,[3]],4];
flatArray(nestedArray)

Javascript Function to return Integer Array

function flatIntigerArray(array){
    return JSON.stringify(array).replace(/[\[\]]/g,'').split(",").map(Number);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment