Arthur
Arthur

Reputation: 3506

Remove all duplicates and undefined in arrays. Ramda.js

I have a such data structure:

{
  '123': [1,1,3,2,undefined],
  '321': [3,3,3,2,undefined,undefined],
  '425': [null,2,2,4,2,null,null]
}

I want to add item to group array and then check for undefined or duplicates exist.
I also have a solution but I think it's not good enough:

check-is-nil.js

const checkIsNil = (groupId, data) => {
  return over(lensProp(groupId), pipe(reject(isNil),uniq), data);
}

add-to-group.js

const addToGroup = (groupId, newObj, data) => {
  return over(lensProp(groupId), append(newObj), data);
};

Using: checkIsNil('123', addToGroup('123', 1, data))
Result:

{
  '123': [1,3,2],
  '321': [3,2],
  '425': [2,4]
}

Upvotes: 0

Views: 1787

Answers (1)

Hitmands
Hitmands

Reputation: 14179

reject is nil should do the job, you could eventually use value => value === undefined if you want to keep null values.

const clean = R.map(
  R.pipe(R.reject(R.isNil), R.uniq),
);

const data = {
  '123': [1,1,3,2,undefined],
  '321': [3,3,3,2,undefined,undefined],
  '425': [null,2,2,4,2,null,null]
};


console.log(
  clean(data),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>

Upvotes: 2

Related Questions