There are various methods to remove objects from an array in JavaScript.
1. Using Array filter() Method
The filter()
method is a functional way to remove an object from an array. It creates a new array containing only the elements that meet a specified condition.
let students = [ { name: "Akash", age: 30 }, { name: "Rakesh", age: 32 }, { name: "Ayush", age: 27 } ]; let filteredStudent = students.filter(student => student.age !== 27); console.log(filteredStudent); /* Output: [ { name: 'Akash', age: 30 }, { name: 'Rakesh', age: 32 } ] */
2. Using Array splice() Method
The splice()
method modifies the original array by removing or replacing existing elements.
let students = [ { name: "Akash", age: 30 }, { name: "Rakesh", age: 32 }, { name: "Ayush", age: 27 } ]; // Find the index of the object to remove let index = students.findIndex(student => student.age === 27); if (index !== -1) { students.splice(index, 1); } console.log(students); /* Output: [ { name: 'Akash', age: 30 }, { name: 'Rakesh', age: 32 } ] */
3. Using Array findIndex() and slice() Methods
Combining findIndex()
with slice()
allows you to create a new array without the object to be removed.
let students = [ { name: "Akash", age: 30 }, { name: "Rakesh", age: 32 }, { name: "Ayush", age: 27 } ]; let index = students.findIndex(student => student.age === 27); let updatedStudents = [ ...students.slice(0, index), ...students.slice(index + 1) ]; console.log(updatedStudents); /* Output: [ { name: 'Akash', age: 30 }, { name: 'Rakesh', age: 32 } ] */
4. Using for Loop
A for
loop provides a manual approach to removing an object by iterating through the array.
let students = [ { name: "Akash", age: 30 }, { name: "Rakesh", age: 32 }, { name: "Ayush", age: 27 } ]; for (let i = 0; i < students.length; i++) { if (students[i].age === 27) { students.splice(i, 1); break; // Stop the loop after removing the object } } console.log(students); /* Output: [ { name: 'Akash', age: 30 }, { name: 'Rakesh', age: 32 } ] */
5. Using reduce() Method
The reduce()
method allows you to build a new array while filtering out the object to be removed.
let students = [ { name: "Akash", age: 30 }, { name: "Rakesh", age: 32 }, { name: "Ayush", age: 27 } ]; let updatedStudents = students.reduce((acc, student) => { if (student.age !== 27) { acc.push(student); } return acc; }, []); console.log(updatedStudents); /* Output: [ { name: 'Akash', age: 30 }, { name: 'Rakesh', age: 32 } ] */
6. Using Lodash’s _.remove() Method
If you’re using Lodash, its _.remove()
method is a convenient way to remove objects from an array.
const _ = require('lodash'); let students = [ { name: "Akash", age: 30 }, { name: "Rakesh", age: 32 }, { name: "Ayush", age: 27 } ]; _.remove(students, student => student.age === 27); console.log(students); /* Output: [ { name: 'Akash', age: 30 }, { name: 'Rakesh', age: 32 } ] */