I have object below:
let menu = [
{name: 'Hambuger_1', categories: ['cheese', 'mushroom'] },
{name: 'Hamburger_2', categories: ['cheese', 'bacon', 'tomato']}
]
And I need an array categories = [cheese, mushroom, bacon, tomato]
I'm using _.uniqBy but it's not considering the arrays as unique, how can I get an array of the unique values for all categories?
I'm using Angular 12 and Firestore, so I have the code like below, but of course as I have arrays, all are diferent:
this.categories$ = this.fbs.getProducts().pipe(map(data => _.uniqBy(data,'category')))
CodePudding user response:
Get the array of categories using Array.flatMap(), and pass the array through a Set to make in unique:
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)
With lodash, use _.flatMap() to get the items, then use _.uniq() to remove duplicates:
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>
