Ramesh
Ramesh

Reputation: 13266

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]}

Upvotes: 1

Views: 413

Answers (2)

th3n3wguy
th3n3wguy

Reputation: 3747

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))
});

Upvotes: 1

Ramesh
Ramesh

Reputation: 13266

I solved it using a sequence of operations.

  1. used get to fetch the array at the specified path.
  2. used slice to get a sliced array till specified index.
  3. used slice to get second array after specified index.
  4. used concat to merge first and second array.
  5. used set to set the array at the specified path.
    const arrayData = get(path, state);
    if (arrayData && index < arrayData.length) {
      const firstSet = slice(0, payload.index, arrayData);
      console.log("array data after slice", arrayData);
      const secondSet = slice(payload.index + 1, arrayData.length, arrayData);

      const newState = set(
        path,
        concat(firstSet, secondSet),
        state
      );
    } else {
       return {...state}
    }

Upvotes: 0

Related Questions