 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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
 