Search code examples
javascriptarraysoopsplice

Why does the splice() array method always deletes all objects following the selected index in Javascript?


I'm currently studying Javascript and the teacher asked us to create a program that allows users to create, edit and delete hotels using object arrays.

I managed to created the showHotels() function without any issue but I'm having troubles deleting a specific hotel from the created array as when I use the splice() method it deletes the object selected but also all the following ones.

The user will have to enter the name of the hotel in order to delete it, we therefore do not know the index of the object.

I am only allowed to use Visual Studio Code and nothing else to write my code.


import { Hotel } from "./hotels.js"
document.getElementById('createHotel').addEventListener('click', createHotel)
document.getElementById('deleteHotel').addEventListener('click', deleteHotel)
document.getElementById('showHotel').addEventListener('click', showHotel)
document.getElementById('editHotel').addEventListener('click', editHotel)

let myHotelArray = []

function createHotel() {

    const hotelName = prompt(`Please enter the name of hotel:`, `W Hotel`)
    const numberOfRooms = prompt(`Please enter the number of rooms:`, `68`)
    const numberOfFloors = prompt(`Please enter the number of floors:`, `12`)
    const totalArea = prompt('Please enter the total area of the hotel:', `250`)

    myHotelArray.push(new Hotel(hotelName, numberOfRooms, numberOfFloors, totalArea))
}


function showHotel() {
    let hotelsFormated = []

    for (let i = 0; i < myHotelArray.length; i++) {
        hotelsFormated.push(`${myHotelArray[i].toString()} <br><br>`);
    }

    document.getElementById('hotels').innerHTML = hotelsFormated.join('')
    console.log(myHotelArray)

}


function deleteHotel() {

    const selectHotel = prompt(`Please enter the name of the hotel you'd like to delete:`)
    const hotelIndex = myHotelArray.findIndex(i => i.hotelName === selectHotel)

    if (hotelIndex >= 0) {
        myHotelArray.splice(hotelIndex)
    }
    else {
        alert("This hotel couldn't be found. Please try again")
    }

    function editHotel() {

    }

}

Solution

  • As mention in mdn Array.splice can receive 2 arguments:

    1. start: Zero-based index at which to start changing the array (dont know what the zero-based mean but use the start argument as any natural Number)

    2. deleteCount: An integer indicating the number of elements in the array to remove from start.

    I think adding deleteCount in your statment like this myHotelArray.splice(hotelIndex, 1) will solve it.

    The splice method will remove from the list and return all the items from hotelIndex to hotelIndex+deletCount.