user3349850 user3349850 - 5 months ago 13
jQuery Question

unique attribute count json

i have a json file as below

{"Teams": [
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
]}


Whats the best way to extract the unique attribute values of f3 .

Here in our example I should store the unique f3 attribute in an array that is array should have
["Jun-2016","May-2016","Aug-2016"]

Answer

Use Array#reduce method

var data= {"Teams": [
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
]};

var res = data.Teams.reduce(function(arr, ele) {
  // check element already exist if not push the value to the array
  if (arr.indexOf(ele.f3) === -1) arr.push(ele.f3);
  return arr;
  // set initial value as empty array
}, []);

console.log(res);