splice in js code example
Example 1: replace array element javascript
// Replace 1 array element at index with item
arr.splice(index,1,item);
Example 2: remove element from array javascript
let fruit = ['apple', 'banana', 'orange', 'lettuce'];
// ^^ An example array that needs to have one item removed
fruit.splice(3, 1); // Removes an item in the array using splice() method
// First argument is the index of removal
// Second argument is the amount of items to remove from that index and on
Example 3: javascript splice
let arr = ['foo', 'bar', 10, 'qux'];
// arr.splice(<index>, <steps>, [elements ...]);
arr.splice(1, 1); // Removes 1 item at index 1
// => ['foo', 10, 'qux']
arr.splice(2, 1, 'tmp'); // Replaces 1 item at index 2 with 'tmp'
// => ['foo', 10, 'tmp']
arr.splice(0, 1, 'x', 'y'); // Inserts 'x' and 'y' replacing 1 item at index 0
// => ['x', 'y', 10, 'tmp']
Example 4: splice javascritp
let colors = ['red', 'blue', 'green'];
let index_element_to_be_delete = colors.indexOf('green');
colors.splice(index_element_to_be_delete);
//Colors now: ['red', 'blue']
Example 5: splice javascript
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
months.splice(0, 1);
// removes 1 element at index 0
console.log(months);
// expected output: Array ["Feb", "March", "April", "May"]
Example 6: remove from array javascript
let numbers = [1,2,3,4]
// to remove last element
let last_num = numbers.pop();
// numbers will now be [1,2,3]
// to remove first element
let first_num = numbers.shift();
//numbers will now be [2,3]
// to remove at an index
let number_index = 1
let index_num = numbers.splice(number_index,1); //removes 1 element at index 1
//numbers will now be [2]
//these methods will modify the numbers array and return the removed element