0

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.

0

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! I will note that it is missing a closing parenthesis on the nested if. I can't submit an edit that is less than 6 chars though, lol
0

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)

1 Comment

I should have had it in the original question, but I am not able to use lodash or add any new dependencies into the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.