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"]
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"]
1// Remove single item
2function removeItemOnce(arr, value) {
3 var index = arr.indexOf(value);
4 if (index > -1) {
5 arr.splice(index, 1);
6 }
7 return arr;
8}
9
10// Remove all items
11function removeItemAll(arr, value) {
12 var i = 0;
13 while (i < arr.length) {
14 if (arr[i] === value) {
15 arr.splice(i, 1);
16 } else {
17 ++i;
18 }
19 }
20 return arr;
21}
22
23// Usage
24console.log(removeItemOnce([2, 5, 9, 1, 5, 8, 5], 5));
25console.log(removeItemAll([2, 5, 9, 1, 5, 8, 5], 5));
1let originalArray = [1, 2, 3, 4, 5];
2
3let filteredArray = originalArray.filter((value, index) => index !== 2);
1// remove element at certain index without changing original
2let arr = [0,1,2,3,4,5]
3let newArr = [...arr]
4newArr.splice(1,1)//remove 1 element from index 1
5console.log(arr) // [0,1,2,3,4,5]
6console.log(newArr)// [0,2,3,4,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))