I'm looking for a way to filter / reject objects in a collection based on the value of a chosen property. Specifically I need to filter out objects that contain duplicate values for that chosen property. I need to convert the property value to lower case and trim the whitespace.
I already have my method for removing the duplicates but I can't figure out how to include the lowercase conversion and the trim.
removeDuplicates: function (coll, attr) {
var uniques = _.map(_.groupBy(coll, function (obj) {
return obj[attr];
}), function (grouped) {
return grouped[0];
});
return uniques;
}
Any help would be appreciated.
If the collection is defined like this
var array = [{
name: "thefourtheye"
}, {
name: "theFOURtheye"
}, {
name: "thethirdeye"
}];
You should be using _.uniq
function, like this
var attr = "name";
console.log(_.unique(array, false, function(currenObject) {
return currenObject[attr].toLowerCase();
}));
# [ { name: 'thefourtheye' }, { name: 'thethirdeye' } ]
As per the signature,
uniq_.uniq(array, [isSorted], [iterator])
the second parameter is tell if the collection is already sorted. This is important, because if the collection is sorted, there are algorithms which can find the unique data very efficiently.
the third parameter, should be a function, which can transform the data to get the key value to compare. As we see in the example, we actually pick the name
property from the individual objects and convert them to lower case letters. So, this lower cased name will represent this object and if two lowercased names are the same, then those objects will be considered as the duplicate of each other.