How to remove an object that matches a filter from a JavaScript array using array.splice(index, howMany) method.

Ghost Together
4 min readDec 22, 2020

--

Functions used in this tutorial:

  • array.some — check if at least one item exists in array.
  • array.findIndex — find index of an object in array of objects.
  • array.splice(index, howManyToDelete) — split array at index and remove n-number of items past that point, return an item or list of items that were removed.

Sometimes you need to remove an object from an array that contains properties that match a value (or values.)

This tutorial explores one practical use case for this.

What is a practical use case for removing objects from JavaScript array?

One of those use cases is storing association between user and event. For example, when user “likes” a tweet, we store relationship between user id and tweet id. This entry is stored in Mongo (or any other) database. When user “unlikes” the tweet, we need to remove that entry from Array object in event relationship map.

In my case I had to remove entry from array when developing Semicolon (www.semicolon.dev). Here’s the example of removing object from JavaScript array and what it was used for:

There are many ways of removing an object from a JavaScript array. This tutorial shows how to remove an object with two properties. The removal of the object will occur only if it matches two values provided in a filter object.

let relationships = [
{ userid: 1, tweetid: 2 }, // user 1 likes tweet 2
{ userid: 2, tweetid: 2 }, // user 2 likes tweet 2
{ userid: 3, tweetid: 4 }, // user 3 likes tweet 4
]

Let’s say we want to remove 2nd item:

let filter = { userid: 2, tweetid: 2 }

Basically filter is an object that works as a filter for the item we want to…

--

--

Ghost Together

Ghost Together @ https://semicolon.dev is an alternative to Twitter. Sign up to meet other makers of things.