Distinct Records in Object Array

(Last Updated On: )

Sometimes you need to determine the distinct objects in an array or distinct values in array. There are so many ways to do this. One way which I have used at times can be a bit slow depending on the size of your array.
From my investigation there is a lodash version that is much better. Once I do some testing I will update this but for now here is an example.
I expanded on the idea from Stack Exchange.

  1. var distinct = function(objectArray, param){
  2.       var distinctResult = [];
  3.  
  4.       $.each(objectArray, function(i, currentObject){
  5.             if (param !== null) {
  6.                   if (distinctResult.filter(function(v) { return v[param] == currentObject[param]; }).length == 0)
  7.                   {
  8.                         distinctResult.push(currentObject);
  9.                   }
  10.             } else {
  11.                   if(!exists(distinctResult, currentObject))
  12. {
  13.       distinctResult.push(currentObject);
  14. }
  15.             }
  16.       });
  17.  
  18.       return distinctResult;
  19. };
  20.  
  21. var exists = function(arr, object){
  22. var compareToJson = JSON.stringify(object);
  23. var result = false;
  24. $.each(arr, function(i, existingObject){
  25. if(JSON.stringify(existingObject) === compareToJson) {
  26. result = true;
  27. return false; // break
  28. }
  29. });
  30.  
  31. return result;
  32. };