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
3//Get index of the number 5
4const index = array.indexOf(5);
5//Only splice if the index exists
6if (index > -1) {
7 //Splice the array
8 array.splice(index, 1);
9}
10
11//array = [2, 9]
12console.log(array);
1const cars = ['farrari', 'Ice Cream'/* It is not an car */, 'tata', 'BMW']
2
3//to remove a specific element
4cars.splice(colors.indexOf('Ice Cream'), 1);
5
6//to remove the last element
7cars.pop();
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);
1/* there are 3 ways to do so
21) pop(), which removes the last element
32) shift(), which removes the first element
43) splice(), which removes any element with a specified index.
5of these only splice() takes parameters. the first parameter it takes is the
6index of the element to be removed, an integer. the second is the number of
7elements to be removed, again integer. the third and fourth etc. are optional,
8which is to be used if you want to replace them. Example: */
9let numbers = [1, 2, 3, 4, 5];
10numbers.pop(); // removes 5
11numbers.shift(); // removes 1
12let threeIndex = numbers.indexOf(3); // used for long arrays
13numbers.splice(threeIndex, 1); // without replacement
14numbers.splice(threeIndex, 1, 7) // 3 will now be replaced by 7