Last active
September 8, 2016 01:00
-
-
Save towkir/e6194c6c40c3275db18e807d7dab85df to your computer and use it in GitHub Desktop.
This script takes a nested array of integer numbers and returns a flat array
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Arrays</title> | |
<style> | |
body { | |
font-family: monospace; | |
margin: 50px; | |
} | |
input, button { | |
border: 1px solid black; | |
line-height: 25px; | |
font-size: 15px; | |
font-weight: bold; | |
padding: 5px; | |
width: 400px; | |
} | |
button { | |
border: none; | |
background: lightgreen; | |
width: auto; | |
} | |
#result { | |
padding: 10px; | |
font-size: 150%; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Convert Nested Arrays to Flat Array:</h1> | |
<p>Enter your nested array:</p> | |
<p> | |
<input type="text" id="nestedArray"/> | |
<button type="button" id="generate">Generate Flat Array</button> | |
</p> | |
<p> | |
Here is the flat Array: | |
</p> | |
<p id="result"></p> | |
<script type="text/javascript"> | |
var nestedRawArray = []; | |
var flatArray = []; | |
function arrayGenerator() { | |
nestedRawArray = JSON.stringify(nestedRawArray); | |
nestedRawArrayPortion = nestedRawArray.split(","); | |
function combine(smallPart){ | |
smallPart = smallPart.split(""); | |
if (smallPart.length>1){ | |
data = ""; | |
for (i=0; i<smallPart.length; i++){ | |
if(!isNaN(parseInt(smallPart[i]))){ | |
data += smallPart[i].toString(); | |
} | |
} | |
return (parseInt(data)); | |
} else { | |
return (parseInt(smallPart[0])); | |
} | |
} | |
for (j=0; j<nestedRawArrayPortion.length; j++){ | |
flatArray.push(combine(nestedRawArrayPortion[j])); | |
} | |
} | |
function validateAndReturnArray(){ | |
try { | |
nestedRawArray = document.getElementById("nestedArray").value; | |
JSON.parse(nestedRawArray); | |
nestedRawArray = JSON.parse(nestedRawArray); | |
arrayGenerator(); | |
if (flatArray.length > 0){ | |
document.getElementById("result").style="color:green;"; | |
document.getElementById("result").innerHTML= JSON.stringify(flatArray); | |
} | |
flatArray = []; | |
} catch(error) { | |
if (error instanceof SyntaxError) { | |
document.getElementById("result").style="color:red;"; | |
document.getElementById("result").innerHTML="Please check the syntax of your array."; | |
} | |
} | |
} | |
document.getElementById("generate").addEventListener("click", validateAndReturnArray); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment