Wednesday, April 12, 2017

How to get distinct values of an array in Javascript

   
    I see this question comes up a lot in the forums, usually people suggests to use a newer ES6 feature to solve this problem or they suggest to use third party javascript polyfill. I think both suggestions are useless and lazy way to solve this problem. All browsers do not support ES6 yet, and you shouldn't get a polyfill just to solve a simple problem like this.

    Since the client side programming has been getting complex, probably you don't have an array of numbers or strings like [1,2,3,2] or ['Apple', 'Banana']. I am guessing you have an array of Json objects  and you want to get the distinct values of a property from a Json object array.

   Here is my suggestion if you are looking for a solution. I have attached the following function to the array object, so this function will be available in all array objects in your project. Also you can find a link to a demo page at the bottom of this article.
 

 

Let's say our array's name is myarray.
distinct function can handle simple arrays
myarray.distinct() gives you the distinct values of an array.

distinct function also handles any array of Json objects.
myarray.distinct('name') gives you the distinct name property values in a json array.
I have created a demo of this function If you like to see it in action.

No comments:

Post a Comment