【问题标题】:Remove duplicate from array while mapping映射时从数组中删除重复项
【发布时间】:2021-03-22 21:52:50
【问题描述】:

是否可以在 map 函数中删除重复的数组。我正在使用 Jsx 并且我有一个字符串数组,我希望尽可能直截了当,但如果我必须这样做,我会采用不同的方式。我会给你看代码。如果您有任何建议,我们将不胜感激。


<aside>
    {tags.map((item, index) => {
    console.log(item.node.category)
    let set = []
    set.push(item.node.category)
    let mine = new Set(set) //this was my poor attempt
    console.log(mine)
    return (
    <>
    <Link
    key={index}
    to={`/blog/categoria/${item.node.category.trim()}`}
    className="category"
    >
    {item.node.category}
    </Link>
    </>
    )
    })}
</aside>



【问题讨论】:

标签: javascript arrays reactjs mapping jsx


【解决方案1】:

有一种方法可以在映射时删除数组的重复项,那就是使用 lodash _.uniq(),但我没有这样做。我(愚蠢的我)必须先抓取我感兴趣的数组

 let tagsonly = []

  let tags = data.allDatoCmsBlog.edges

  tags.forEach(element => {
    tagsonly.push(element.node.category)
  })


然后使用reduce函数

 var tagssorted = tagsonly.reduce(function (p, c, i, a) {
    if (p.indexOf(c) == -1) p.push(c)
    else p.push(null)
    return p
  }, [])

tagssorted 是我想要的

【讨论】:

    猜你喜欢
    • 2012-04-17
    • 2011-06-29
    • 2018-04-25
    • 2021-09-22
    • 2011-01-04
    相关资源
    最近更新 更多