1

How can I iterate through object properties and remove duplicates from an array that is the value of that object property?

Original object

var navObjects = {
    'Components': ['x', 'y', 'x'],
    'Document': ['z', 'z', 'z', 'q'],
    'Utilities': ['a', 'b', 'c']
}

Desired object

navObjects: {
    'Components': ['x', 'y'],
    'Document': ['z','q'],
    'Utilities': ['a', 'b', 'c']
}

What I've tried

for (let i = 0; i < Object.values(navObjects).length; i++) {

    let obj = Object.values(navObjects)[i];

    Object.values(obj).filter((item, index) => obj.indexOf(item) === index);
    console.log(obj);

}

The arrays remain unchanged after running this block.

3 Answers 3

4

You can do it using the Set constructor and the spread syntax:

const navObjects = {
  'Components': ['x', 'y', 'x'],
  'Document': ['z', 'z', 'z', 'q'],
  'Utilities': ['a', 'b', 'c']
};

for (const key in navObjects) {
  navObjects[key] = [...new Set(navObjects[key])];
}

console.log(navObjects);

Sign up to request clarification or add additional context in comments.

2 Comments

Nice. This wins.
This will only work if we assume that the object only has array members and we intend to remove duplicates for all of them.
0

This code will help you to achieve your objective.

var newNavObjects = {}
var existObjects = {}
for(let key in navObjects) {
    let objects = navObjects[key];
    newNavObjects[key] = [];
    existObjects[key] = {};
    for(let object of objects) {
        if (!existObjects[key][object]) {
            existObjects[key][object] = 1;
            newNavObjects[key].push(object);
        }
    }
}
delete existObjects;
console.log(newNavObjects);

I create new variable for efficiency. If we use indexOf to check value inside array exist of not. It will heavier than we check an target variable key in this case existObjects. Still this not the best solution but this sure will do. :)

Comments

0

You can create a Set to remove duplicates and get values() in order to convert it back to an array, like:

(new Set(['z', 'z', 'z', 'q'])).values()

Let's make a function of it:

function removeDuplicates(input) {
    return (new Set(input)).values();
}

and then use it:

var navObjects = {
    'Components': removeDuplicates(['x', 'y', 'x']),
    'Document': removeDuplicates(['z', 'z', 'z', 'q']),
    'Utilities': removeDuplicates(['a', 'b', 'c'])
}

1 Comment

I wonder about the reason this answer was downvoted. I tested it and it worked. If someone would shed light on the reason, I would be grateful.

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.