-1

From the following object

items = [{
    title = 'title 1',
    category = 'foo'
  },
  {
    title = 'title 5',
    category = 'bar'
  },
  {
    title = 'title n',
    category = 'bar'
  },
]

which

  • I receive dynamically at runtime
  • can have any length
  • where each category field can have one of up to items.length values

I want to get the set of all different values for the field category.

In the example above, the result of

get_all_possible_categories(items)

would be

['foo','bar'].

How can I implement

get_all_possible_categories(items) ?
Oblomov
  • 8,953
  • 22
  • 60
  • 106

2 Answers2

2

You could take a Set and map all values of the wanted property.

At the end take an array and spread syntax ... for building a new array. The spread sytax takes the values of an iterable and insert them as parameters.

var items = [{ title: 'title 1', category: 'foo' }, { title: 'title 5', category: 'bar' }, { title: 'title n', category: 'bar' }],
    values = [...new Set(items.map(o => o.category))];

console.log(values);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Just map the values back to an array, using a Set to get unique values

items = [{
    title : 'title 1',
    category : 'foo'
  },
  {
    title : 'title 5',
    category : 'bar'
  },
  {
    title : 'title n',
    category : 'bar'
  }
];

function get_all_possible_categories(arr) {
  return [...new Set(arr.map( x => x.category))];
}

var result = get_all_possible_categories(items);

console.log(result);
adeneo
  • 312,895
  • 29
  • 395
  • 388