0

I'm very new to react, so be please be gentle. I have a relatively flat JS file that contains some questions. It looks like this:

export default [
{
  category: 'General Questions',
  title: 'Question 1?',
  content:'Answer 1',
},
{
  category: 'Pricing',
  title: 'Question 2?',
  content:'Answer 2',
},

I have multiple categories throughout the file. What I'd like to do is create a list of all the unique categories. So the user would only see

  • General Questions
  • Pricing
  • Etc.

I'm able to get all of the content using a filter function here:

getFaqContent() {
    return filter(item => {
        return item.featured;
    }, Faqs);
}

How can I just get the unique categories?

Lz430
  • 307
  • 2
  • 7
  • 16
  • Just a quick note, you can use much smaller syntax when writing that filter: `Faqs.filter(item => item.featured)`. – Blue Nov 02 '18 at 15:08

3 Answers3

5

You can use .filter() again to just select the unique categories (Grabbed from some help from this question):

const questions = [
{
  category: 'General Questions',
  title: 'Question 1?',
  content:'Answer 1',
},
{
  category: 'Pricing',
  title: 'Question 2?',
  content:'Answer 2',
},
{
  category: 'Pricing',
  title: 'Question 2?',
  content:'Answer 2',
}];

const cats = questions.map(q => q.category);

console.log(
  cats.filter((q, idx) => 
    cats.indexOf(q) === idx)
);

Additionally, you can use ES6's new Set() functionality as well, and convert it back to an array using ES6 spread syntax:

const questions = [
{
  category: 'General Questions',
  title: 'Question 1?',
  content:'Answer 1',
},
{
  category: 'Pricing',
  title: 'Question 2?',
  content:'Answer 2',
},
{
  category: 'Pricing',
  title: 'Question 2?',
  content:'Answer 2',
}];

const cats = [...new Set(questions.map(q => q.category))];

console.log(cats);
Blue
  • 22,608
  • 7
  • 62
  • 92
  • This works great! I can console all the unique cats. However, I'm getting an error when printing them out: Each child in an array or iterator should have a unique "key" prop. Is it because I don't have a UID for each question? – Lz430 Nov 02 '18 at 17:03
  • 1
    Set your key to the value (Should be unique anyway) – Blue Nov 02 '18 at 17:04
  • I got it using the `map` method – Lz430 Nov 02 '18 at 17:05
  • See this for more info on the key prop: https://reactjs.org/docs/lists-and-keys.html – Blue Nov 02 '18 at 17:05
2

An elegant solution using ES6:

const categories = yourList.map(x => x.category);
const uniqueCategories = [...new Set(categories)]; 
Riccardo Gai
  • 421
  • 1
  • 6
  • 19
0

You can use reduce() you can call uniqueBy(array, 'category') where array will be your data

function uniqueBy(arr, prop){
   return arr.reduce((a, d) => {
   if (!a.includes(d[prop])) { a.push(d[prop]); }
      return a;
   }, []);
} 

var categories = uniqueBy(array, 'category')
console.log(ages); //['General Questions', 'Pricing'  ]
murtuza hussain
  • 458
  • 1
  • 7
  • 18