Removing a specific element from an array

34 Views Asked by At

I have an array called hotelList where the user is asked by prompt to enter

name; numberOfRooms; numberOfFloors; surfaceOfHotel;

now, for example when I want to remove an hotel which right in the middle of the array, I am tryiong this code:

function eliminateHotel() {
  const userPrompt = prompt(
    "introduce el nombre del hotel que quieras eliminar"
  );
  console.log(hotelList.indexOf(userPrompt === hotelList.name));
  console.log (hotelList.splice(hotelList.indexOf(userPrompt === hotelList.name)))
  console.log(hotelList)

but when I try to do it, it will only eliminate the last element of the array. Not the one I chose.

Can you please help?

Thanks a lot

1

There are 1 best solutions below

2
Mouayad_Al On

try to use findIndex:

const index = hotelList.findIndex(el => userPrompt  == el.name);
if(index > -1) hotelList.splice(index,1);