Skip to content Skip to sidebar Skip to footer

How To Get The Count Of Duplicate Value Assigned To Same Key In Json Array - Javascript/nodejs

Hi Guys i need small help in getting this solved. If this is a duplicate post please point me to the original question. Here I have an JSON array of elements Ex : var consume = [{'

Solution 1:

Finally I wrote Answer to my question in pure javascript.

Thanks for your support guys who ever tried to guide me to solve my question

var consume = [{"key":"Test1"},{"key":"Test2"},{"key":"Test3"},{"key":"Test1"},{"key":"Test3"},{"key":"Test1"}]
 
 var temp = [];
 
 var produce = [];
 
 for(var i=0;i<consume.length;i++){
   if(temp.indexOf(consume[i].key) == -1){
   		temp.push(consume[i].key);
      var _data = {};
      _data.name = consume[i].key;
      _data.count = 1;
      
      produce.push(_data);
   }else{
     for(var j=0;j<produce.length;j++){
     		if(produce[j].name === consume[i].key){
        		var _x = parseInt(produce[j].count) + 1;
            produce[j].count = _x;
        }
     }
   }
 }

console.log(produce);

Solution 2:

Hmm.. these days when it comes to object property thingies i am intrigued with ES6 iterators. This is how i would approach this job;

var consume = [{"key":"Test1"},{"key":"Test2"},{"key":"Test3"},{"key":"Test1"},{"key":"Test3"},{"key":"Test1"}],
    reduced = consume.reduce((p,c) => (p[c.key] ? p[c.key]++ : p[c.key] = 1,p),{}),
    produce = [];
reduced[Symbol.iterator] = function*(){
                             var oKeys = Object.keys(this);
                             for(var key of oKeys) yield {name : key, count: this[key]};
                           };
produce = [...reduced];
console.log(produce);

Post a Comment for "How To Get The Count Of Duplicate Value Assigned To Same Key In Json Array - Javascript/nodejs"