I have following data array:
const data = [
{ year: 1900, title: 'test 1' },
{ year: 2000, title: 'test 2' },
{ year: 2000, title: 'test 3' },
{ year: 2000, title: 'test 4' },
];
My aim is to get an array of years where each given year appear more than twice:
[2000]
the countBy is fairly easy to achieve by:
_.chain(data)
.countBy('year')
.value()
which returns the following object:
{'1900': 1, '2000': 3}
I’m stumbling upon the filtering part. I tried the following but it returns me an empty array:
_.chain(data)
.countBy('year')
.filter((o) => {
o > 2;
})
.value();
What would be the correct way?
You only have a small typo in your code:
should be
or
Otherwise, you will always return
undefined
, therefore everything is filtered out.Replace
_.filter()
with_.pick()
because filter would return only the values ([3]
), and not keys (the years). You should also return from the callback –o => o > 2
.Afterwards, get the an array of the keys (the years), and map them to numbers (if needed).