I have an Array with some numeric values. I want to display them but I also have a user input which should be displayed after the respective element in the array. My approach works fine but seems really overcomplicated to me. I created a fiddle:
http://jsfiddle.net/sjoy8p59/1/
var numbers = [2, 4, 8, 12, 42, 120, 612, 69];
var input = 32;
var flag = false;
var output = "";
for (i = 0; i < numbers.length; i++) {
if (numbers[i] < input) {
output += numbers[i]+", ";
} else {
if (flag == false) {
output += input + ", ";
flag = true;
} else {
output += numbers[i]+", ";
}
}
}
document.getElementById("output").innerHTML = output;
So the value 32 from input should be displayed after the 12 and before the 42 from the array. I use a for loop and a boolean with an if clause to detect whether the Array element is larger or smaller than the input and then add it all together and display it.
How can I do it better and cleaner?
EDIT: I figured out there is a mistake in my code because it skipped one element in the array