Friday, 13 March 2015

How to remove duplicate from an array and get count of duplicated .

Using very minimum code we can achieve this.

Sample json data

 
var data = [
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'John'
        age:'60'
    },
    {
        name : 'Prakash'
        age:'60'
    },
    {
        name : 'Johnson'
        age:'60'
    },
    {
        name : 'Martha'
        age:'60'
    },

]


Jquery

 

var counts = [];
   jQuery.each(data, function(key,value) {
     if (!counts.hasOwnProperty(value.name)) {
  counts[value.name] = 1;
   } else {
  counts[value.name]++;
   }
 });
 

Do a console.log(counts) you can see duplicated names and count .If you want in an array format you can try below one

 

var finalResults = [];
     for(var cntVal in counts) {
  finalResults.push([cntVal, counts[cntVal]]);
}
 

Demo

Related Posts

1. Create responsive highchart

2. About CK-Editor

3. Dynamic height for side bar


No comments :

Post a Comment