检查映射数组中的项是否共享值

Pix*_*omo 6 javascript arrays time duplicates reactjs

我正在使用React和moment.js构建新闻源.使用.map我正在渲染带有标题和内容的项目.我想检查一件商品是否在同一年份和另一件商品中发布.如果是这种情况,我想隐藏第二项标题.

请看我的小提琴

目前我的代码呈现:

2018年3月

新闻第一项

2018年3月

新闻第二项

2017年9月

新闻第三项

2017年6月

新闻第四项

由于第一项和第二项共享同一个月和一年,我想这样渲染:

2018年3月

新闻第一项

新闻第二项

2017年9月

新闻第三项

2017年6月

新闻第四项

根据这个答案,我试图找到具有重复类名的节点,但我不是那里:

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' ]
Run Code Online (Sandbox Code Playgroud)

也许我会以错误的方式解决这个问题.map,首先使用它是一个坏主意?

更新

感谢所有的好答案,很难在他们之间挑选,因为他们都运作良好.自从他第一次提供一个有效的例子以来,我必须接受David Ibl的回答.

Dav*_*Ibl 1

你可以这样做: https: //jsfiddle.net/2e27jvvh/

render() {
const arr = new Array();
return( 
    <div>
    {this.state.news.map(item => {
        const yearMonth = moment(item.date).format("MMMM YYYY");
        const yearM = moment(item.date).format("MMMM_YYYY");
        if (arr.indexOf(yearMonth) < 0){
            arr.push(yearMonth);
          return (
          <div className={'months ' + yearM}>
              <h2>{yearMonth}</h2>
              <p>{item.content}</p> 
          </div>
            ) 
        } else {
            return (
          <div className={'months ' + yearM}>
              <p>{item.content}</p> 
          </div>
            ) 
        }

        }) 
    }
 </div>
)
}
Run Code Online (Sandbox Code Playgroud)

也许您应该根据之前的年份和月份对项目进行排序,以确保正确的行为,即使项目最初未排序。但这适用于你的例子。