I'm building a news feed using React and moment.js. Using .map
I'm rendering items with a title and content. I'd like to check if an item was posted in the same year and month as another item. If this is the case I want to hide the second items title.
Currently my code renders this:
March 2018
news item one
March 2018
news item two
September 2017
news item three
June 2017
news item four
Since item one and two share the same month and year I would like to render like this instead:
March 2018
news item one
news item two
September 2017
news item three
June 2017
news item four
Based on this answer I've tried to find nodes with duplicate class names but I'm not quite there:
let monthNodes = [...document.querySelectorAll('.months')];
let months = []
monthNodes.map(month => {
months.push(month.className)
})
const count = names =>
names.reduce((a, b) =>
Object.assign(a, {[b]: (a[b] || 0) + 1}), {})
const duplicates = dict =>
Object.keys(dict).filter((a) => dict[a] > 1)
console.log(count(months)) // {March_2018: 2, December_2017: 1, November_2017: 1}
console.log(duplicates(count(months))) // [ 'March_2018' ]
Maybe I'm going about this the wrong way and using .map
in the first place is a bad idea?
Update
Thanks for all the great answers, it was hard to pick between them as they all work well. I have to accept David Ibl's answer since he was first to provide a working example.