How can I remove an element from a list, with lodash?

JavascriptArraysObjectLodash

Javascript Problem Overview


I have an object that looks like this:

var obj = {
    "objectiveDetailId": 285,
    "objectiveId": 29,
    "number": 1,
    "text": "x",
    "subTopics": [{
        "subTopicId": 1,
        "number": 1
    }, {
        "subTopicId": 2,
        "number": 32
    }, {
        "subTopicId": 3,
        "number": 22
    }]
}
var stToDelete = 2;

I have lodash installed in my application for other things. Is there an efficient way to use lodash to delete the entry: {"subTopicId":2, "number":32} from the obj object?

Or is there a javascript way to do this?

Javascript Solutions


Solution 1 - Javascript

As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove, like this

_.remove(obj.subTopics, {
    subTopicId: stToDelete
});

Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not.

_.remove(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId === stToDelete;
});

Alternatively, you can create a new array by filtering the old one with _.filter and assign it to the same object, like this

obj.subTopics = _.filter(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId !== stToDelete;
});

Or

obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToKeep});

Solution 2 - Javascript

Just use vanilla JS. You can use splice to remove the element:

obj.subTopics.splice(1, 1);

Demo

Solution 3 - Javascript

you can do it with _pull.

_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});

check the reference

Solution 4 - Javascript

You can now use _.reject which allows you to filter based on what you need to get rid of, instead of what you need to keep.

unlike _.pull or _.remove that only work on arrays, ._reject is working on any Collection

obj.subTopics = _.reject(obj.subTopics, (o) => {
  return o.number >= 32;
});

Solution 5 - Javascript

There are four ways to do this as I know

const array = [{id:1,name:'Jim'},{id:2,name:'Parker'}];
const toDelete = 1;

The first:

_.reject(array, {id:toDelete})

The second one is :

_.remove(array, {id:toDelete})

In this way the array will be mutated.

The third one is :

_.differenceBy(array,[{id:toDelete}],'id')
// If you can get remove item 
// _.differenceWith(array,[removeItem])

The last one is:

_.filter(array,({id})=>id!==toDelete)

I am learning lodash

Answer to make a record, so that I can find it later.

Solution 6 - Javascript

The easiest and most convenient way -

_.without([2, 1, 2, 3], 1, 2);
// => [3]

_.without documentation.

Solution 7 - Javascript

In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:

  _.remove(obj.subTopics, (currentObject) => {
        return currentObject.subTopicId === stToDelete;
    });

OR

obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
    return currentObject.subTopicId !== stToDelete;
});

Solution 8 - Javascript

lodash and typescript

const clearSubTopics = _.filter(obj.subTopics, topic => (!_.isEqual(topic.subTopicId, 2)));
console.log(clearSubTopics);

Solution 9 - Javascript

Here is the simple lodash function with array and deleting it with the index number.

index_tobe_delete = 1

fruit = [{a: "apple"}, {b: "banana"}, {c: "choco"}]
_.filter(fruit, (value, key)=> {
return (key !== index_tobe_delete)
})

Solution 10 - Javascript

You can use removeItemFromArrayByPath function which includes some lodash functions and splice

/**
 * Remove item from array by given path and index
 *
 * Note: this function mutates array.
 *
 * @param {Object|Array} data (object or array)
 * @param {Array|String} The array path to remove given index
 * @param {Number} index to be removed from given data by path
 *
 * @returns {undefined}
 */

const removeItemFromArrayByPath = (data, arrayPath, indexToRemove) => {
  const array = _.get(data, arrayPath, []);
  if (!_.isEmpty(array)) {
    array.splice(indexToRemove, 1);
  }
};

You can check the examples here: https://codepen.io/fatihturgut/pen/NWbxLNv

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamantha J T StarView Question on Stackoverflow
Solution 1 - JavascriptthefourtheyeView Answer on Stackoverflow
Solution 2 - JavascriptAndyView Answer on Stackoverflow
Solution 3 - JavascriptsemirturgayView Answer on Stackoverflow
Solution 4 - JavascriptXeltorView Answer on Stackoverflow
Solution 5 - JavascriptmqliutieView Answer on Stackoverflow
Solution 6 - JavascriptFarhan SyedView Answer on Stackoverflow
Solution 7 - JavascriptPranav SinghView Answer on Stackoverflow
Solution 8 - JavascriptUliana PavelkoView Answer on Stackoverflow
Solution 9 - JavascriptAnupam MauryaView Answer on Stackoverflow
Solution 10 - JavascriptFatih TurgutView Answer on Stackoverflow