1

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

Ramesh
  • 13,043
  • 3
  • 52
  • 88

2 Answers2

1

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))
});
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30
  • I can remove 2 slices and concat with this reject – Ramesh May 06 '20 at 02:18
  • I'm glad that you were able to find this useful. If you wish for this to be your answer, it would be helpful for others in the future if you were to choose this as the selected answer. Glad I could be of help! – th3n3wguy May 06 '20 at 03:21
  • I have upvoted the answer. I will validate it in code and once done, will mark this as an answer – Ramesh May 06 '20 at 03:30
  • Do you know how to do this with lodash fp? I am unable to get the parameter into predicate – Ramesh May 07 '20 at 01:29
  • @Ramesh => I am sorry, but I have not done much with the Lodash FP side of things. I would probably ask another question, refer to this one, and then see if you can get a Lodash FP answer. – th3n3wguy May 07 '20 at 01:37
0

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}
    }
Ramesh
  • 13,043
  • 3
  • 52
  • 88