How to gracefully determine that an element exists in an array and then remove the element and add it if it doesn't exist?

there is a requirement to remove an element from the array when it exists, and to add the element to the array when it does not exist.
this is how I implement it. Is there a more elegant or convenient way to write it? Please do not hesitate to give us advice!

selectTag(row, id) {
    if (row.tagId.indexOf(id) > -1) {
         row.tagId = row.tagId.filter(n => n !== id)
    } else {
        row.tagId.push(id)
    }
}
Mar.02,2021

Whether or not there is a better way to delete elements in your array is open to question. Now that you have called the indexof method, you should delete the elements with the splice method, which is tantamount to traversing the array again.

selectTag(row, id) {
    row.tagId.includes(id) ? row.tagId = row.tagId.filter(n => n !== id) : row.tagId.push(id)
}
Menu