I'm new, so this will be a stupid question. I got an assignment to create a global array, in which I will need to import objects, as they're added to an input field in the html document. Then from there, I need to update the current list on the html document, but I need to add the middle element of the array to the list, and then empty the array. My question is, how do I find the middle index and add it to the array? I tried the following code
const ulList = document.querySelector("ul");
const liElement = document.createElement("li");
liElement.innerHTML = `${globalArray[globalArray.length / 2 - 1].key} ${globalArray[globalArray.length / 2 - 1].manufacturer} ${globalArray[globalArray.length / 2 - 1].model}`
ulList.appendChild(liElement);
globalArray.splice(globalArray[globalArray.length / 2 - 1], 1);
function getArrayMidKey(myArray) {
let midKeyIndex = Math.floor(myArray.length / 2)
return midKeyIndex;
}
let snacks = array("Cake", "Soda", "Apples", "Doritos");
midSnack = snacks[getArrayMidKey(snacks));
// midSnack --> "Soda"
This gives you the middle key of any given array..
If the array has 5 items, it will give you item number 2, if it has 6 or 7 items - it gives you item number 3 and so on.
Math.floor(globalArray.length / 2)
globalArray[Math.floor(globalArray.length / 2)]
Try this