xxxxxxxxxx
var array = ["Item", "Item", "Delete me!", "Item"]
array.splice(2,1) // array is now ["Item","Item","Item"]
xxxxxxxxxx
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car");//get "car" index
//remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red","blue","green"]
xxxxxxxxxx
var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
//removing element using splice method --
//arr.splice(index of the item to be removed, number of elements to be removed)
//Here lets remove Sunday -- index 0 and Monday -- index 1
myArray.splice(0,2)
//using filter method
let itemToBeRemoved = ["Sunday", "Monday"]
var filteredArray = myArray.filter(item => !itemToBeRemoved.includes(item))
xxxxxxxxxx
//remove any item from array
const data = ['first', 'second', 'last'];
const filtered_data = data.filter((item) => return item !== 'second');
console.log(filtered_data) // ['first', 'last']
xxxxxxxxxx
let originalArray = [1, 2, 3, 4, 5];
let filteredArray = originalArray.filter((value, index) => index !== 2);
xxxxxxxxxx
let a=[1,2,3,4,5,6,7,8]
//if we want to remove an element with index x
a.splice(x,1)
xxxxxxxxxx
pop - Removes from the End of an Array.
shift - Removes from the beginning of an Array.
splice - removes from a specific Array index.
filter - allows you to programatically remove elements from an Array.
xxxxxxxxxx
const array = [2, 5, 9, 5, 20, 5];
console.log(array);
const index = array.indexOf(5);
if (index > -1) { // only splice array when item is found
array.splice(index, 1); // 2nd parameter means remove one item only
}
// array = [2, 9]
console.log(array);
Run code snippetHide results
xxxxxxxxxx
let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];
// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']
// remove the last element from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();
//get removed element
console.log(removedElement); // 'sleep'
console.log(dailyActivities); // ['work', 'eat']