Categories
JavaScript Answers

How to Remove an Element from a JavaScript Array with Lodash?

Spread the love

Sometimes, we want to remove an element from a list with Lodash.

In this article, we’ll look at how to remove an element from a JavaScript array with Lodash.

Use the remove Method

One way to remove an element from a JavaScript array is to use the Lodash remove method.

For instance, we can write:

const obj = {
  "objectiveDetailId": 285,
  "objectiveId": 29,
  "number": 1,
  "text": "x",
  "subTopics": [{
    "subTopicId": 1,
    "number": 1
  }, {
    "subTopicId": 2,
    "number": 32
  }, {
    "subTopicId": 3,
    "number": 22
  }]
}
const stToDelete = 2;
_.remove(obj.subTopics, {
  subTopicId: stToDelete
});
console.log(obj)

to remove the obj.subTopics entry with the subTopicId set to 2.

To do this, we call the remove method with the obj.subTopics property as the first argument.

And we pass in an object with the entry with the subTopicId we want to delete from obj.subTopics .

The removal operation will be done in place.

And the removed item will be returned.

Therefore, obj is now:

{
  "objectiveDetailId": 285,
  "objectiveId": 29,
  "number": 1,
  "text": "x",
  "subTopics": [
    {
      "subTopicId": 1,
      "number": 1
    },
    {
      "subTopicId": 3,
      "number": 22
    }
  ]
}

Instead of passing in an object as the 2nd argument of remove , we can also pass in a predicate function with the condition of the items we want to remove.

To do this, we write:

const obj = {
  "objectiveDetailId": 285,
  "objectiveId": 29,
  "number": 1,
  "text": "x",
  "subTopics": [{
    "subTopicId": 1,
    "number": 1
  }, {
    "subTopicId": 2,
    "number": 32
  }, {
    "subTopicId": 3,
    "number": 22
  }]
}
const stToDelete = 2;
_.remove(obj.subTopics, (currentObject) => {
  return currentObject.subTopicId === stToDelete;
});
console.log(obj)

We call remove with the same first argument.

But the 2nd argument is replaced with a predicate function that returns the condition of the object we want to remove.

And so e get the same result as in the previous example.

Conclusion

We can remove an element from an array in an object with Lodash with the remove method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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