3

I want to delete object from array by id using Ramda. For example:

const arr = [
  {id: '1', name: 'Armin'},
  {id: '2', name: 'Eren'}, <- delete this object
  {id: '3', name: 'Mikasa'}
];
Arthur
  • 3,056
  • 7
  • 31
  • 61
  • Have you tried anything? Its a fairly simple operation. – Rajesh Aug 08 '19 at 10:00
  • @Rajesh, sure, I've tried to use R.filter(), R.reject(), but I still new in Ramda – Arthur Aug 08 '19 at 10:03
  • Possible duplicate: https://stackoverflow.com/questions/29254470/ramda-how-to-filter-based-on-a-value-in-a-nested-array – Rajesh Aug 08 '19 at 10:03
  • Try `R.filter(({ id }) => id !== '2', arr)`. For more info, refer: https://ramdajs.com/0.19.1/docs/#filter. Also a pointer, when you ask a question, please share your attempt in question. That makes a requirement, problem and we could help accordingly – Rajesh Aug 08 '19 at 10:04

4 Answers4

7

You can user filter function, with a composed functions propEq & not

const result = filter(
  compose(
   not,
   propEq('id', 2)
  ),
  array,
)
console.log(result)
The Reason
  • 7,705
  • 4
  • 24
  • 42
  • 3
    I don't see how `filter + complement(propEq)` would be a better solution than using `reject(propEq)`... – Hitmands Aug 08 '19 at 10:38
  • @Hitmands there are a lot of ways in a ramda to handle such case, regarding `reject` it is the exactly same as `filter + complement(propEq)` check the implementation on [github](https://github.com/ramda/ramda/blob/master/source/reject.js) – The Reason Aug 09 '19 at 07:20
  • 1
    Of course it is, the issue is about readability... at high level, reject reads better than negating filter... and that is why reject exists. – Hitmands Aug 09 '19 at 07:27
7

You can use both filter or reject:

R.reject(o => o.id === '2', arr);

R.filter(o => o.id !== '2', arr);
Skyrocker
  • 970
  • 8
  • 15
6

You can use reject.

The reject() is a complement to the filter(). It excludes elements of a filterable for which the predicate returns true.

let res = R.reject(R.propEq('id', '2'))(arr);
Charlie
  • 22,886
  • 11
  • 59
  • 90
3

// you could create a generic rejectWhere function
const rejectWhere = (arg, data) => R.reject(R.whereEq(arg), data);


const arr = [
  {id: '1', name: 'Armin'},
  {id: '2', name: 'Eren'}, // <- delete this object
  {id: '3', name: 'Mikasa'}
];


console.log(
  'result', 
  rejectWhere({ id: '2' }, arr),
);

// but also
// rejectWhere({ name: 'Eren' }, arr),
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>
Hitmands
  • 13,491
  • 4
  • 34
  • 69