Last active
March 29, 2018 15:11
-
-
Save jaydlawrence/ffae92806ba58b73b1dac8437e7df7db to your computer and use it in GitHub Desktop.
A quick test to get a recursive array flatten function in JS.
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
<script type="text/javascript"> | |
const processString = () => { | |
try { | |
const arrayString = document.forms["myForm"]["array"].value; | |
const jsonDecodedArray = JSON.parse(arrayString); | |
const resultArray = arrayFlatten(jsonDecodedArray); | |
const resultArrayString = JSON.stringify(resultArray); | |
document.getElementById("result").innerHTML = `Result: ${resultArrayString}`; | |
} | |
catch(error) { | |
document.getElementById("result").innerHTML = `Error: ${error.message}`; | |
} | |
return false; | |
}; | |
const arrayFlatten = unsortedArray => { | |
let resultArray = [] | |
unsortedArray.forEach(element => { | |
if (element instanceof Array) return resultArray = resultArray.concat(arrayFlatten(element)); | |
return resultArray.push(element); | |
}); | |
return resultArray; | |
}; | |
</script> | |
<form name="myForm" onsubmit="return processString()" > | |
<input name="array" /> | |
<input type="submit" /> | |
</form> | |
<div id="result"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment