0

I have the following data that is an array of nested objects:

"categories": [
  {
   "id": 1,
   "name": "Category 1",
   "years": [
    { "id": 1, "name": "1" },
    { "id": 2, "name": "2" }
   ]
  },
  {
   "id": 2,
   "name": "Category 2",
   "years": [
    { "id": 2, "name": "2" },
    { "id": 3, "name": "3" }
   ]
  }
 ]

I want to extract unique years in a separate array (desired output):

[
  { "id": 1, "name": "1" },
  { "id": 2, "name": "2" },
  { "id": 3, "name": "3" },
]

When I map out the years, I'm getting an array of arrays, how should I extract the unique objects for years?

let years = categories.map( (c) => { return c.years })
1
  • Use categories.reduce to build up the collection of unique years Commented Aug 22, 2019 at 17:49

2 Answers 2

2

You can use a Map to filter duplicate years from the array of values using id as the key, and reduce() on both categories and years using the map as the accumulator:

const categories = [{
    "id": 1,
    "name": "Category 1",
    "years": [
      { "id": 1, "name": "1" },
      { "id": 2, "name": "2" }
    ]
  },
  {
    "id": 2,
    "name": "Category 2",
    "years": [
      { "id": 2, "name": "2" },
      { "id": 3, "name": "3" }
    ]
  }
];

const years = categories.reduce(
  (map, category) => category.years.reduce(
    (map, year) => map.set(year.id, year),
    map
  ),
  new Map()
);

console.log([...years.values()]);

Sign up to request clarification or add additional context in comments.

Comments

2

You can use reduce and Map

let data = [{"id": 1,"name": "Category 1","years": [{ "id": 1, "name": "1" },{ "id": 2, "name": "2" }]},{"id": 2,"name": "Category 2","years": [{ "id": 2, "name": "2" },{ "id": 3, "name": "3" }]}]
  
let final = data.reduce((op,{years}) => {
  years.forEach(({id, name}) => {
    let key = id + '-' + name
    op.set(key, op.get(key) || {id, name})
  })
  return op
},new Map())

console.log([...final.values()])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.