public
Last active

Finds Unique Values for Provided Properties on an Object Array

  • Download Gist
UniquePropertyValues.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
var Cars = [
{ Make: 'BMW', Model: '850ci', Color: 'Green' },
{ Make: 'Rover', Model: 'SD1', Color: 'Black' },
{ Make: 'VM', Model: 'Golf', Color: 'Bronze' },
{ Make: 'Volvo', Model: 'P1800', Color: 'Green' },
{ Make: 'BMW', Model: '850ci', Color: 'Green' },
{ Make: 'Rover', Model: 'SD1', Color: 'Black' },
{ Make: 'VM', Model: 'Golf', Color: 'Bronze' },
{ Make: 'Volvo', Model: 'P1800', Color: 'Green' }
];
 
/**
* Finds Unique Values for Provided Properties
* @param {Array.<Object>} Objects
* @param {Array.<string>} Properties
* @return {Array.<Array>} Unique Values for Properties
*/
var UniquePropertyValues = function(Objects, Properties) {
var UniqueProperties = [];
for(var i = Objects.length - 1; i >= 0; i--) {
for(var j = 0, l = Properties.length; j < l; j++) {
if(UniqueProperties[j] == void 0)
UniqueProperties[j] = [];
if(
Objects[i][Properties[j]] != void 0 &&
UniqueProperties[j].indexOf(Objects[i][Properties[j]]) == -1
)
UniqueProperties[j].push(Objects[i][Properties[j]]);
}
}
return UniqueProperties;
};
 
 
console.log(UniquePropertyValues(Cars, ['Make', 'Model', 'Color']));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.