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?

Pierre Trzaska
  • 105
  • 1
  • 3
  • 9
  • Do you have lots of duplicate values in the array? If so, you might want to filter out duplicates first... – evolutionxbox May 31 '17 at 10:41
  • What should exactly the format of `listChapter` be? – Slim May 31 '17 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](https://stackoverflow.com/a/16747921/6304441) – glhrmv May 31 '17 at 10:44
  • lodash or underscore has functions to make unique elements (_.uniq). – vijayst May 31 '17 at 10:44

6 Answers6

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;
}, []);
fubar
  • 16,918
  • 4
  • 37
  • 43
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);
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))];
0

This approach is faster, because of less iterations:

const listChapter = Object.keys(datas.reduce((ac, el) => {
    ac[el.category] = true
    return ac
}, {}))
Slim
  • 1,924
  • 1
  • 11
  • 20
0

arr is the whole array.

for(var i = 0; i < data.length; i++) {
            if(arr[i] == data.category) {
              remove item here;
            }
          }
Anusha
  • 1
  • 1
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)));
Tom
  • 1,636
  • 2
  • 13
  • 21