The mistake was in your delete portion.
In delete, you were using the number instead of the index of the number.
Here is the corrected code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let arr = [];
for (let i = 0; i < Infinity; i++) {
var command = prompt("Введите команду");
var arrays = command.split(" ");
var index = arrays[0];
var name = arrays[1];
if (index == "add") {
arr.push(name);
var res = arr.join(" ");
console.log(res);
} else if (index === "delete" || index === "del") {
console.log(name)
const index = arr.indexOf(name)
if(index !== -1){
arr.splice(index, 1);
} else {
console.log("Value not present in list")
}
console.log(arr);
}
if (index === "stop") {
break;
}
}
console.log(arr);
</script>
</body>
</html>
Now, if you want to remove all the instances from the list, it would be better to use sets.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let arr = new Set();
for (let i = 0; i < Infinity; i++) {
var command = prompt("Введите команду");
var arrays = command.split(" ");
var index = arrays[0];
var name = arrays[1];
if (index == "add") {
arr.add(name);
} else if (index === "delete" || index === "del") {
const avail = arr.delete(name)
if(!avail){
console.log("Value not in list")
}
}
if (index === "stop") {
break;
}
}
console.log(arr);
</script>
</body>
</html>
Lastly, If you want to use arrays to store similar values but remove all of them when user gives del
. Use the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let arr = [];
for (let i = 0; i < Infinity; i++) {
var command = prompt("Введите команду");
var arrays = command.split(" ");
var index = arrays[0];
var name = arrays[1];
if (index == "add") {
arr.push(name);
} else if (index === "delete" || index === "del") {
arr = arr.filter(n => n !== name)
}
if (index === "stop") {
break;
}
}
console.log(arr);
</script>
</body>
</html>