Reputation: 679
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.
Upvotes: 1
Views: 67
Reputation: 3842
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);
Upvotes: 4
Reputation: 77053
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'])
}
Upvotes: 0
Reputation: 750
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. :)
Upvotes: 0