Remove an object from an array in JavaScript
This post will discuss how to remove an object from an array in JavaScript.
There are several ways to remove an object from an array in JavaScript:
1. Using Array.prototype.filter() function
The recommended method in JavaScript is to use the filter() method, which creates a new array with the object that passes the specified predicate.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
let obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; let filtered = obj.filter(o => o.name !== 'John'); console.log(filtered); /* Output: [ { name: 'Max', age: 23 }, { name: 'Caley', age: 18 } ] */ |
2. Using Underscore/Lodash Library
Similarly, you can use the _.filter method of the Underscore or Lodash library, which offers similar functionality.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var _ = require('underscore'); let obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; let filtered = _.filter(obj, o => o.name !== 'John'); console.log(filtered); /* Output: [ { name: 'Max', age: 23 }, { name: 'Caley', age: 18 } ] */ |
The opposite of the _.filter is the _.reject method, which can be used in the following manner to return elements of the collection that fails the predicate.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var _ = require('underscore'); let obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; let filtered = _.reject(obj, o => o.name === 'John'); console.log(filtered); /* Output: [ { name: 'Max', age: 23 }, { name: 'Caley', age: 18 } ] */ |
3. Using jQuery
With jQuery, you can use the $.grep() method, which removes items from an array that does not pass a provided test.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); let obj = [ { name: 'Max', age: 23 }, { name: 'John', age: 20 }, { name: 'Caley', age: 18 } ]; let filtered = $.grep(obj, o => o.name !== 'John'); console.log(filtered); /* Output: [ { name: 'Max', age: 23 }, { name: 'Caley', age: 18 } ] */ |
That’s all about removing an object from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)