remove item from array javascript indexOF 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: javascript remove from array by index

//Remove specific value by index
array.splice(index, 1);

Example 3: array remove index from array

const array = [2, 5, 9];

//Get index of the number 5
const index = array.indexOf(5);
//Only splice if the index exists
if (index > -1) {
  //Splice the array
  array.splice(index, 1);
}

//array = [2, 9]
console.log(array);

Example 4: js remove if

ar = [1, 2, 3, 4];
ar = ar.filter(item => !(item > 3));
console.log(ar) // [1, 2, 3]

Example 5: locate and delete an object in an array

var people = [
    {name: 'Billy', age: 22},
    {name: 'Sally', age: 19},
    {name: 'Timmy', age: 29},
    {name: 'Tammy', age: 15}
];
_.remove(people, function(e) {
    return e.age < 21
});
console.log(people);

// Output
// [ { name: 'Billy', age: 22 }, { name: 'Timmy', age: 29 } ]

Example 6: how can i remove a specific item from an array

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 2
const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length))
// ["a", "b", "d", "e", "f"]

Tags:

C Example