2

I am using this code to read all the values from each object with the key "category":

const listChapter = datas.map((data) => console.log(data.category))

datas is an array of Objects, and there are 45 objects.

The problem is that when I console.log that, i have many duplicates values, you can see that below:

console.log results

I want to have one unique value of each category. How can I do that?

4
  • Do you have lots of duplicate values in the array? If so, you might want to filter out duplicates first... Commented May 31, 2017 at 10:41
  • What should exactly the format of listChapter be? Commented May 31, 2017 at 10:42
  • You can map over data to get each category into an array and then filter that array and remove any duplicate values, assuming you want an array of strings. Read this answer Commented May 31, 2017 at 10:44
  • lodash or underscore has functions to make unique elements (_.uniq). Commented May 31, 2017 at 10:44

6 Answers 6

1

Filter duplicates from the data before you iterate through them.

var unique = datas.reduce(function(unique, data) { return unique.indexOf(data.category) === -1 ? unique.concat(data.category) : unique; }, []); 
Sign up to request clarification or add additional context in comments.

1 Comment

It does the job. Thanks !
1

You also can do the trick with the Set:

let data = ['Alfa', 'Alfa', 'Beta', 'Gamma', 'Beta', 'Omega', 'Psi', 'Beta', 'Omega']; let arr = [... new Set(data)]; // Or = Array.from(new Set(data)); console.log(arr); 

Edit: I forgot that you have array of objects. In that case:

let data2 = [ {'category': 'Alfa'}, {'category': 'Alfa'}, {'category': 'Beta'} ] let set = new Set(); data2.forEach((data) => { set.add(data.category); }); let arr2 = [... set]; console.log(arr2); 

Comments

1

This is minor improvement of Tomek's answer. (I am not able comment yet.)

const arr = [ {'category': 'Alfa'}, {'category': 'Alfa'}, {'category': 'Beta'} ]; const unique = [...new Set(arr.map(item => item.category))]; 

Comments

0

This approach is faster, because of less iterations:

const listChapter = Object.keys(datas.reduce((ac, el) => { ac[el.category] = true return ac }, {})) 

Comments

0

arr is the whole array.

for(var i = 0; i < data.length; i++) { if(arr[i] == data.category) { remove item here; } } 

Comments

0

Here's an alternative one-liner using filter() (just for fun):

console.log(datas.filter((data, i, a) => i === a.findIndex(data2 => data.category === data2.category))); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.