4
let arr = [
{
 id: 100,
 name: 'bmw'
},
{
 id: 101,
 name" 'porsche'
}
];

let selected = [{id: 100}];

What is the Ramda way of getting a filtered list F based on the inputs (list, selected)?

Zack Tarr
  • 851
  • 1
  • 8
  • 28
user898788
  • 109
  • 7
  • Possible duplicate of https://stackoverflow.com/questions/37091448/ramda-get-objects-from-array-by-comparing-with-each-item-in-another-array ? – JayJay Mar 06 '18 at 02:00

2 Answers2

2

Ramda has a function built-in which directly handles finding the single value. If you want to find all the ones in a list, you'll need to extend it a bit. But whereEq tests an object to see if all the properties match those in a sample object. So you can do something like this:

const {find, whereEq, map} = R;

const arr = [
  {id: 100, name: 'bmw'},
  {id: 101, name: 'porsche'},
  {id: 102, name: 'ferrari'},
  {id: 103, name: 'clunker'}
]

console.log(find(whereEq({id: 101}), arr))

const choose = (all, selected) => map(sel => find(whereEq(sel), all), selected)

console.log(choose(arr, [{id: 101}, {id: 103}]))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Depending upon how you plan to use it, you might want to wrap choose in curry.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
1

My take would be to break it down into a few parts.

// a function to grab the the id out of selected (index of 0, key of 'id')
const selectedId = path([0, 'id'])

const selectedValue = (selected, options) =>
  filter(propEq('id', selectedId(selected)), options)

selectedValue(selected, arr) // [{"id": 100, "name": "bmw"}]

That’s a little difficult to read for my liking, so I’d then regroup some of the functions, and also use head to get the result out of the array

const hasIdOf = pipe(selectedId, propEq('id'))

const selectedValueB = (selected, options) => pipe(
  filter(hasIdOf(selected))),
  head
)(options)

selectedValueB(selected, arr) // {"id": 100, "name": "bmw"}

propEq(‘id’) returns a function that takes two more parameters. A value to test an id property against, and an object with an id property

pipe composes many functions together, in this case, it’s passing options to filter(...), and the result of that to head

head returns item at index 0

You can break up the functions in many ways. Whatever you find most readable/reusable

Have a play with the above code here

Clarence Lee
  • 141
  • 6
  • Oh boy, I don't have enough reputation to upvote or comment on Scott's answer :O But I certainly learned something new there. Thanks Scott. – Clarence Lee Feb 28 '18 at 07:38