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

How to remove object from JavaScript array by id

Today I’m going to show you how to remove an object from a JavaScript array by its id using the Array findIndex() and splice() methods. Let's get started!

Remove object from array JavaScript by id. #

First, use the findIndex() method on your JavaScript array which will return the index of any element that matches a specified condition within it.

You can pass in this condition as a function with each item being iterated over until one is found which returns true or -1 if none are found. For example :

<script>
 let myArr = [{id: 1}, {id: 2}, {id: 3}]
 let result = myArr.findIndex(item => item.id === 2);
 console.log(result) // output : 1
</script>

Since, this is our second element in our array so we know what position it holds inside our data structure.

Next, once we have determined what position our desired object resides at within out data structure, we can then use splice() method to delete it.

The Splice() method allows us to specify two parameters; firstly specifying where we want start deleting elements and secondly how many elements should be deleted starting from that point onwards.

In order for us to delete just one single object based off its ID, we simply set both these parameters as the following example.

"myArr.splice(result, 1)" – here result represents whatever value was returned when calling Find Index earlier on whilst "1" specifies how many items should be removed starting at given location.
<script>
 let myArr = [{id: 1}, {id: 2}, {id: 3}]
 let result = myArr.findIndex(item => item.id === 2);
 myArr.splice(result,1); 
 console.log(myArr); // output : {id: 1}, {id: 3}
</script>

And there you have it! We've successfully removed an object from a Javascript array by its Id using the findIndex() & splice() methods! Hope this helps.

save
listen
AI Answer
Write Your Answer
loading
back
View All