1var colors = ["red","blue","car","green"];
2var carIndex = colors.indexOf("car");//get "car" index
3//remove car from the colors array
4colors.splice(carIndex, 1); // colors = ["red","blue","green"]
1const array = [2, 5, 9];
2
3console.log(array);
4
5const index = array.indexOf(5);
6if (index > -1) {
7 array.splice(index, 1);
8}
9// array = [2, 9]
10console.log(array);
1function removeItemOnce(arr, value) {
2 var index = arr.indexOf(value);
3 if (index > -1) {
4 arr.splice(index, 1);
5 }
6 return arr;
7}
8
9function removeItemAll(arr, value) {
10 var i = 0;
11 while (i < arr.length) {
12 if (arr[i] === value) {
13 arr.splice(i, 1);
14 } else {
15 ++i;
16 }
17 }
18 return arr;
19}
20// Usage
21console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
22console.log(removeItemAll([2,5,9,1,5,8,5], 5))
1function removeItemOnce(arr, value) {
2 var index = arr.indexOf(value);
3 if (index > -1) {
4 arr.splice(index, 1);
5 }
6 return arr
7}
8
9function removeItemAll(arr, value) {
10 var i = 0;
11 while (i < arr.length) {
12 if (arr[i] === value) {
13 arr.splice(i, 1);
14 } else {
15 ++i;
16 }
17 }
18 return arr;
19}
20// Usage
21console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
22console.log(removeItemAll([2,5,9,1,5,8,5], 5))
1let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])