Remove Object from Array Using Javascript

Remove Object from Array using JavaScript

Working with arrays is a common task in JavaScript, and sometimes we need to remove specific objects from an array. In this blog post, we will explore different methods to remove objects from an array using JavaScript.

Method 1: Using the filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. We can use this method to filter out the object we want to remove.


const array = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 3, name: "Bob" }
];

const removeObjectFromArray = (arr, obj) => {
  return arr.filter(item => item.id !== obj.id);
};

const objectToRemove = { id: 2, name: "Jane" };
const newArray = removeObjectFromArray(array, objectToRemove);
console.log(newArray);

The output of the above code will be:


[
  { id: 1, name: "John" },
  { id: 3, name: "Bob" }
]

Method 2: Using the splice() method

The splice() method changes the contents of an array by removing or replacing existing elements. We can use this method to remove the object from the array by its index.


const array = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 3, name: "Bob" }
];

const removeObjectFromArray = (arr, obj) => {
  const index = arr.findIndex(item => item.id === obj.id);
  if (index !== -1) {
    arr.splice(index, 1);
  }
  return arr;
};

const objectToRemove = { id: 2, name: "Jane" };
const newArray = removeObjectFromArray(array, objectToRemove);
console.log(newArray);

The output of the above code will be:


[
  { id: 1, name: "John" },
  { id: 3, name: "Bob" }
]

Method 3: Using the findIndex() and slice() methods

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. We can use this method to find the index of the object we want to remove, and then use the slice() method to create a new array without that object.


const array = [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" },
  { id: 3, name: "Bob" }
];

const removeObjectFromArray = (arr, obj) => {
  const index = arr.findIndex(item => item.id === obj.id);
  if (index !== -1) {
    return arr.slice(0, index).concat(arr.slice(index + 1));
  }
  return arr;
};

const objectToRemove = { id: 2, name: "Jane" };
const newArray = removeObjectFromArray(array, objectToRemove);
console.log(newArray);

The output of the above code will be:


[
  { id: 1, name: "John" },
  { id: 3, name: "Bob" }
]

These are three different methods to remove objects from an array using JavaScript. Choose the method that suits your specific use case and start removing objects from your arrays with ease!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *