How to remove object from array in javascript

Learn how to remove an object from an array in javascript.

Arrays in javascript are not like arrays in other programming language, they are dynamic in size and can store multiple different data types.

So objects are also stored in array and we will see how you can remove an object from the array.

Using delete operator

We can use delete operator to delete an object from the array, but it is not advisable to do because delete operator will leave a hole in the array.

Instead of removing the object and shifting other elements it will leave an empty space at that index.

let arr = [123, 'Prashant Yadav', 'India', null, {'abc':'xyz'}, {'pqr': 'stu'}];

delete arr[4];

console.log(arr);
//[123, 'Prashant Yadav', 'India', null, undefined, {'pqr': 'stu'}];

To make it work we have to completely remove the item at that index.


By Splicing the array to remove object

We can use the splice method to remove the object at given index and shift all other elements in the array.

let arr = [123, 'Prashant Yadav', 'India', null, {'abc':'xyz'}, {'pqr': 'stu'}];

arr.splice(4, 1);

console.log(arr);
//[123, 'Prashant Yadav', 'India', null, {'pqr': 'stu'}];

This seems to be working fine but one catch over here is that we are removing items based on array’s index, To make it dynamically filter an object we can create a custom function which will filter the array’s object based on the input.

We will provide the key, value as an input and use Array.filter() method to remove object from array in javascript.

let filterObjects = (key, value) => {
  //Filter array based on the key and value
  return arr.filter((e) => {
    //Check if the current element is of object type
    //And has the key
    if(e && e.hasOwnProperty(key) && e[key] === value){
      return false;
    }

    return true;
  });
};
let arr = [123, 'Prashant Yadav', 'India', null, {'abc':'xyz'}, {'pqr': 'stu'}];

console.log(filterObjects('pqr','stu'));
//[123, 'Prashant Yadav', 'India', null, {'abc': 'xyz'}]

You can modify the above function to filter the nested objects based on your requirement.