Loading...
const i = list.indexOf(item);
list.splice(i, 1);const i = list.indexOf(item);
if (i !== -1) list.splice(i, 1);When the item is missing, indexOf() returns -1 and splice(-1, 1) silently removes the last element.
splice(-1, 1) removes the last item when indexOf() returned -1.splice() in a forward loop and skipping the next element.splice(i) removes everything from i to the end.indexOf() is not -1 before calling splice().toSpliced() or filter() instead of splice().splice() return?An array of the removed elements, or an empty array if nothing was removed.
Pass 0 as the delete count: arr.splice(index, 0, newItem).