delete element from array js by index code example

Example 1: remove a particular element from array

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"]

Example 2: locate and delete an object in an array

// we have an array of objects, we want to remove one object using only the id property
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];
 
// get index of object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);
 
// remove object
apps.splice(removeIndex, 1);

Example 3: delete item from list javascript

const array = [1, 2, 3];
const index = array.indexOf(2);
if (index > -1) {
  array.splice(index, 1);
}

Example 4: remove array elements javascript

let forDeletion = [2, 3, 5]

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!

console.log(arr)
// [ 1, 4 ]

Example 5: remove a value to an array of javascript

var data = [1, 2, 3];

// remove a specific value
// splice(starting index, how many values to remove);
data.splice(1, 1);
// data = [1, 3];

// remove last element
data.pop();
// data = [1, 2];