Inserting into an Array ADDED SEARCH (4:48

by aren_anderson

HTML

<div>
  <b>Enter Array Size:</b> <input type="textbox" id="tbArraySize" value="100" />
  <input type="button" id="btnCreate" value="Create Array" onclick="createArray();" />
</div>
<div>
  <b>Enter Location: </b> <input type="textbox" id="tbInsertIndex" value="20" />
  <b>Enter Value to Insert: </b> <input type="textbox" id="tbInsertValue" value="99" />
  <input type="button" id="btnInsert" value="Insert Into Array" onclick="insertIntoArray();" />
</div>
<div>
  <b>Enter Value to Find: </b> <input type="textbox" id="tbSearchValue" value="20" />
  <input type="button" id="btnSearch" value="Search Array" onclick="searchArray();"/>
</div>

<div id="operations">
</div>
<div id="output">
</div>
<div id="search">
</div>

JavaScript

//global variables for array and output
var array = [];
var d = "";
var o = "";
var s = "";

//function to fill array with values based on value in array size textbox
function createArray() {
  //call function to clear current output display
  clearDisplay();
  //get arraySize value for array
  var arraySize = parseInt(document.getElementById("tbArraySize").value);
  //loop that fills array with random numbers based on the array size value
  for (var i = 0; i < arraySize; i++) {
    array[i] = Math.floor(Math.random() * 100 + 1);
  }
  //call function to display array
  displayArray();
}

//function to clear the display
function clearDisplay() {
  //set output variable to empty string
  array = [];
  d = "";
  o = "";
  s = "";
  //set output div to empty string
  document.getElementById("output").innerHTML = "";
  document.getElementById("operations").innerHTML = "";
  document.getElementById("search").innerHTML = "";
}

//function to display the array
function displayArray() {
  //loop that adds the array value to output string d
  for (var i = 0; i < array.length; i++) {
    d += i + " : " + array[i] + "<br/>";
  }
  
  //attempt to remove undefined array elements
  array.filter(Boolean);
  
  document.getElementById("output").innerHTML = d; 
}


//testing
function insertIntoArray() {
	
  //get index value for insertion
  var index = parseInt(document.getElementById("tbInsertIndex").value);
  //get value to insert at index
  var value = parseInt(document.getElementById("tbInsertValue").value);
  
  //NEW CODE
  insert(array, index, value);
  
  displayArray();
}

//insert value into correct index while shifting current array elements to the right
function insert(array, index, value) {
	//variable for operation counter
  var opsInsert = 0;
  
  d = "Inserting " + value + " at " + index + "<br/>";
  
  //insert WITHOUT splice
  for (i = array.length-1; i >= index; i--){
    if (i > index) {
    	array[i] = array[i-1];
      opsInsert++;
    }
    else if (i ==...