How do I remove an item on click? This is what I currently have:
function deleteUser(name) {
var person = name;
const array = ['John','Mark','Andy'];
const index = array.indexOf(person);
if (index > -1) {
array.splice(index, 1);
}
console.log(array);
}
<button onclick="deleteUser('John')"> Delete User </button>
<button onclick="deleteUser('Mark')"> Delete User </button>
<button onclick="deleteUser('Andy')"> Delete User </button>
I can already remove value on array but I am getting different result.
Ex. When I delete on a value John. I am getting ['Mark','Andy'] but when I delete Mark I am getting ['John','Andy'].
I want to remove the item on array when it is click
-
So you want to make an array with deletedUsers ? And whenever you delete someone you push that user into the deletedUsers arrayKZander– KZander2020年04月24日 13:30:31 +00:00Commented Apr 24, 2020 at 13:30
2 Answers 2
Probably you can define the array outside of the function and using .filter() to remove items. Important thing is .filter() creates a new array so you need to reassign in your function the result. See from the documentation:
The
filter()method creates a new array with all elements that pass the test implemented by the provided function.
Try as the following:
let array = ['John','Mark','Andy'];
const deleteUser = name => {
array = array.filter(e => e !== name);
console.log(array);
}
<button onclick="deleteUser('John')"> Delete User </button>
<button onclick="deleteUser('Mark')"> Delete User </button>
<button onclick="deleteUser('Andy')"> Delete User </button>
I hope this helps!
Comments
You need to define the array outside the function otherwise it get reinitialized every time.
Also the filter method is a great function to do this, however if you want you can still do it with splice too as long you keep the array outside of your function.
var array = ['John','Mark','Andy'];
function deleteUser(name) {
array = array.filter(n => n !== name);
console.log(array);
}
<button onclick="deleteUser('John')"> Delete User John</button>
<button onclick="deleteUser('Mark')"> Delete User Mark </button>
<button onclick="deleteUser('Andy')"> Delete User Andy</button>
2 Comments
indexOf plus splice is more efficient. It doesn't create a new array and stops iterating after a single match is found. The filter solution is more readable imo. In the end it comes down to preference.