2

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

1
  • So you want to make an array with deletedUsers ? And whenever you delete someone you push that user into the deletedUsers array Commented Apr 24, 2020 at 13:30

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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

Note that the 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.
@3limin4t0r Good note, didn't know about the performance. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.