Search code examples
javascriptarrayslodash

How to remove an element from an array using _.set or equivalent


How to remove an element using lodash/fp's set or equivalent method.

I tried

_.set({data:[1,2,3]},"data[1]", undefined)

which results in {data:[1,undefined,3]} where as I would like to get the output as {data:[1,3]}

also tried unset which results in {data:[1,empty,3]}


Solution

  • Here is a clean solution for you. The only thing you need to change is the _.isEqual(idx, 1) for whatever index that you want to remove, or even change it and use an array, if you need by using _.includes([1, 5, 10], idx) instead of the _.isEqual() functionality.

    // Your idea:
    _.set({data:[1,2,3]},"data[1]", undefined)
    
    // Using a simple _.reject() function:
    const newData = _.assign({}, myObj, {
      data: _.reject(myObj.data, (val, idx) => _.isEqual(idx, 1))
    });