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));
1var colors = ["red", "blue", "car","green"];
2
3// op1: with direct arrow function
4colors = colors.filter(data => data != "car");
5
6// op2: with function return value
7colors = colors.filter(function(data) { return data != "car"});
1//you can use two functions depending of what you want to do:
2
3let animals1 = ["dog", "cat", "mouse"]
4delete animals1[1]
5/*this deletes all the information inside "cat" but the element still exists
6so now you'll have this:*/
7console.log(animals1)//animals1 = ["dog", undefined, "mouse"]
8
9//if you want to delete it completely, you have to use array.splice:
10
11let animals2 = ["dog", "cat", "mouse"]
12animals2.splice(1, 1)
13/*the first number means the position from which you want to start to delete
14and the second is how much elements will be deleted*/
15console.log(animals2)//animals2 = ["dog", "mouse"]
16/*Now you don't have undefined
17If you did this:*/
18let animals3 = ["dog", "cat", "mouse"]
19animals3.splice(0, 2)//you'll have this:
20console.log(animals3)//animals 3 = "mouse"
21/*This happens because I put a 2 in the second parameter so it deleted
22two elements from position 0
23Try copying this code in your console and whatch*/
1let value = 3
2
3let arr = [1, 2, 3, 4, 5, 3]
4
5arr = arr.filter(item => item !== value)
6
7console.log(arr)
8// [ 1, 2, 4, 5 ]
9
1let items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
2items.length; // return 11
3items.splice(3,1) ;
4items.length; // return 10
5/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */