Reputation: 154
I have an array that contains custom objects that look like this:
{
field: fieldName,
dataType: usuallyAString,
title: titleForLocalization,
environmentLabel: environmentName
}
There are a couple of other properties on the object, but the only ones that I actually care about are field
and environmentLabel
. I need to filter out any objects that have identical field
and environmentLabel
but don't care about any other properties. The array can have objects that share field
or environmentLabel
, just not both.
Ideally I'd like to use Array.filter
but have yet to figure out how to do it based on two properties. Also, I am limited to es5.
Upvotes: 0
Views: 64
Reputation: 1456
const data = [{
field: 1,
dataType: "usuallyAString",
title: "titleForLocalization",
environmentLabel: 1
},
{
field: 1,
dataType: "usuallyAString",
title: "titleForLocalization",
environmentLabel: 1
},
{
field: 2,
dataType: "usuallyAString",
title: "titleForLocalization",
environmentLabel: 2
}]
var result = _.uniqWith(data, function(arrVal, othVal) {
return arrVal.field=== othVal.field && arrVal.environmentLabel=== othVal.environmentLabel;
});
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
If you are able to use lodash, you can do:
var result = _.uniqWith(data, function(arrVal, othVal) {
return arrVal.field=== othVal.field && arrVal.environmentLabel=== othVal.environmentLabel;
});
console.log(result)
Upvotes: 0
Reputation: 782785
Create another object that contains all the combinations of properties you want to test. Use filter()
and test whether the pair already exists in the object. If not, add the properties to the other object and return true
.
var seen = {};
newArray = array.filter(function(obj) {
if (seen[obj.field]) {
if (seen[obj.field].includes(obj.environmentLabel) {
return false;
} else {
seen[obj.field].push(obj.environmentLabel);
}
} else {
seen[obj.field] = [obj.environmentLabel];
}
return true;
});
Upvotes: 2