I want to delete the exact item in the array but pop will delete the last item. What can I do instead?
const arr = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
var num = prompt("Enter a Number");
for (var i = 0; i < num; i ) {
var day = prompt("Enter Days: ");
if (arr[i].includes(day)) arr.pop(day)
}
console.log(arr);
CodePudding user response:
You can use array.filter to remove unwanted entries from an array. It will leave the original array untouched and return a new array without the values.
var filteredArray = arr.filter((innerDay) => innerDay !== day)
CodePudding user response:
You could start of by prompting for the day you want to delete. Then loop over the array and if the item includes()
it, you could use splice()
to remove the specific item at the index of i
.
const arr = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
var day = prompt("Enter Day: ");
for (var i = 0; i < arr.length; i ) {
if (arr[i].includes(day)) arr.splice(i, 1)
}
console.log(arr);
CodePudding user response:
You firstly need to check if that element (day) is present in the array. If yes, you'll get its index. Use that to safely delete it using splice. I assume the above is what you're trying to achieve. If you are looking for that day according to the order of your question numbers, probably you can follow @axtck's answer.
const arr = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
var num = prompt("Enter a Number");
for (var i = 0; i < num; i ) {
var day = prompt("Enter Days: ");
var index = arr.indexOf(day)
if (index > -1) arr.splice(index, 1)
}
console.log(arr);
CodePudding user response:
You can use filter()
:
const arr = ['monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'sturday', 'sunday'
]
function removeDay(arr, day) {
return arr.filter(el => el !== day);
}
var day = prompt("Enter Day: ");
var newArray = removeDay(arr, day);
console.log(newArray);