javascript find and remove element from array code example

Example 1: javascript find element in array and remove

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

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

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: js remove from array by value

const index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

Example 4: find and delete element from array js

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

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

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