Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu March 01, 2023 › #Array #HowTo

How to remove an object from array JavaScript by value

The most efficient way of removing an object by value is using the filter() method. This method creates a new array that contains all elements that pass the test implemented by the provided function.

Remove an object from array by value using filter method. #

In this case, we want to create a function that will check if our target value matches any of our existing values in our original array and return false for those values so they are excluded from being added into our filtered result set.

<script>
 let arr = [{name:"Red", id:1}, {name:"Green",id:2}, {name:"Blue",id:3}];
 const deleteObjectByValue = (arr, keyToRemove) => {  
      return arr.filter(obj => obj[keyToRemove] !== 'Green');  
 };  

 let newObjArr = deleteObjectByValue(arr,'name');
 console.log("New array ", newObjArr );     
</script>

As you can see above, we used the filter() method which returns only those elements whose condition satisfies.

We passed name as parameter and returned only Objects whose name property doesn't have the value Green. So now we got what exactly was required to removed objects based on some specified criteria like here name property.

Remove item from array by value using splice() method in JavaScript. #

To remove an object from a JavaScript array by value using the splice() method, you can first use the indexOf() method to find the index of the object, and then use the splice() method to remove it from the array. Suppose, you want to remove the object with the name 'Green', you can use the following code.

<script>
 let arr = [{name:"Red", id:1}, {name:"Green",id:2}, {name:"Blue",id:3}];
 let index = arr.map(x => x.name).indexOf('Green');
 arr.splice(index, 1);
 console.log(arr)
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All