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
4 Answers 4
you can use Array filter function
participants.filter((item) => item.username !== username))
2 Comments
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
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.
array.findIndex()as well if you ever need to do more than just filter out something.