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' }
]

Updated on: 21-Nov-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements