0

I have an array like:

var participants = [
  {username: "john", time: null}, 
  {username: "samira", time: null}, 
  {username: "mike", time: null}, 
  {username: "son", time:null}
]

I want to remove an item by username:

const index = participants.map(x => {

  x.map(y => {
      return y.username;
    })
  }).indexOf(username); //get index of username

participants.splice(index, 1);

Hence, index of username returns "-1", therefore participants array becomes 0?

Expected output, by username: 'son':

[
  {username: "john", time: null}, 
  {username: "samira", time: null}, 
  {username: "mike", time: null}
]

UPDATE:

Turns out my array is within an array, like this

Console log array

2
  • what is the expected output Commented Jan 28, 2019 at 15:34
  • Use participants.filter() instead so you don't have to splice(). Your shown code does not work since x is already the item instead of an array you can map again. PS: there's a function called array.findIndex() as well if you ever need to do more than just filter out something. Commented Jan 28, 2019 at 15:35

4 Answers 4

3

you can use Array filter function

participants.filter((item) => item.username !== username))

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

2 Comments

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
What if the array was within another array, as question updated?
0

you can use filter method or in your way with splice and map :

participants.splice(participants.map(x => x.username).indexOf(username),1);

Comments

0

You can use filter function, but filter doesn’t change the original array; so you have to reassign results to the original variable. participants = participants.filter((item) => item.username !== username))

Comments

0

try this

var username = 'son';

for(var i = 0; i < participants.length; i++) {
    if(participants[i].username == username) {
        participants.splice(i, 1);
        i--;
    }
}

NOTE: filter, map and the like offer code readability while for loops are better performing. Choose according to your specific problem.

1 Comment

When using splice inside that kind of loop i remember to decrease i after splice, otherwise if there are two consecutive matching entries the second wont be deleted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.