How to get concatenated list of unique items in array in JS/TS
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>