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));
1//using filter() method => it returns a new array
2data = [1, 2, 3, 4, 5, 6];
3let filteredData = data.filter((i) => {
4 return i > 2
5});
6console.log(filteredData) // [3, 4, 5, 6]
1let fruit = ['apple', 'banana', 'orange', 'lettuce'];
2// ^^ An example array that needs to have one item removed
3
4fruit.splice(3, 1); // Removes an item in the array using splice() method
5// First argument is the index of removal
6// Second argument is the amount of items to remove from that index and on
7
8
1let numbers = [1,2,3,4]
2
3// to remove last element
4let lastElem = numbers.pop()
5
6// to remove first element
7let firstElem = numbers.shift()
8
9// both these methods modify array while returning the removed element
1let numbers = [1,2,3,4]
2
3// to remove last element
4let last_num = numbers.pop();
5// numbers will now be [1,2,3]
6
7// to remove first element
8let first_num = numbers.shift();
9//numbers will now be [2,3]
10
11// to remove at an index
12let number_index = 1
13let index_num = numbers.splice(number_index,1); //removes 1 element at index 1
14//numbers will now be [2]
15
16//these methods will modify the numbers array and return the removed element