![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search by id and remove object from JSON array in JavaScript
Suppose, we have an array of objects that contains data about some movies like this −
const arr = [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, {id: "3", name: "X-Men", type: "action"}, {id: "4", name: "Ordinary People", type: "drama"}, {id: "5", name: "Billy Elliot", type: "drama"}, {id: "6", name: "Toy Story", type: "children"} ];
We are required to write a JavaScript function that takes in one such array as the first argument and an id string as the second argument. Then our function should search for the object by that id, and if the array contains that object, we should remove it from the array.
Example
The code for this will be −
const arr = [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, {id: "3", name: "X-Men", type: "action"}, {id: "4", name: "Ordinary People", type: "drama"}, {id: "5", name: "Billy Elliot", type: "drama"}, {id: "6", name: "Toy Story", type: "children"} ]; const removeById = (arr, id) => { const requiredIndex = arr.findIndex(el => { return el.id === String(id); }); if(requiredIndex === -1){ return false; }; return !!arr.splice(requiredIndex, 1); }; removeById(arr, 5); console.log(arr);
Output
And the output in the console will be −
[ { id: '1', name: 'Snatch', type: 'crime' }, { id: '2', name: 'Witches of Eastwick', type: 'comedy' }, { id: '3', name: 'X-Men', type: 'action' }, { id: '4', name: 'Ordinary People', type: 'drama' }, { id: '6', name: 'Toy Story', type: 'children' } ]
Advertisements