如何在 JS/TS 中获取数组中唯一项的串联列表
How to get concatenated list of unique items in array in JS/TS
我有以下对象:
let menu = [
{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] },
{name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}
]
我需要一个数组categories = [cheese, mushroom, bacon, tomato]
我正在使用 _.uniqBy 但它没有将数组视为唯一,我如何才能获得所有类别的唯一值数组?
我正在使用 Angular 12 和 Firestore,所以我有如下代码,但当然因为我有数组,所以它们都是不同的:
this.categories$ = this.fbs.getProducts().pipe(map(data => _.uniqBy(data,'category')))
使用Array.flatMap()
获取categories
的数组,并通过Set
传递数组使其唯一:
const menu = [{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] }, {name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}]
const result = [...new Set(menu.flatMap(o => o.categories))]
console.log(result)
使用 lodash,使用 _.flatMap()
获取项目,然后使用 _.uniq()
删除重复项:
const menu = [{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] }, {name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}]
const result = _.uniq(_.flatMap(menu, 'categories'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
我有以下对象:
let menu = [
{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] },
{name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}
]
我需要一个数组categories = [cheese, mushroom, bacon, tomato]
我正在使用 _.uniqBy 但它没有将数组视为唯一,我如何才能获得所有类别的唯一值数组?
我正在使用 Angular 12 和 Firestore,所以我有如下代码,但当然因为我有数组,所以它们都是不同的:
this.categories$ = this.fbs.getProducts().pipe(map(data => _.uniqBy(data,'category')))
使用Array.flatMap()
获取categories
的数组,并通过Set
传递数组使其唯一:
const menu = [{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] }, {name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}]
const result = [...new Set(menu.flatMap(o => o.categories))]
console.log(result)
使用 lodash,使用 _.flatMap()
获取项目,然后使用 _.uniq()
删除重复项:
const menu = [{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] }, {name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}]
const result = _.uniq(_.flatMap(menu, 'categories'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>