简体   繁体   中英

How to remove duplicates from an array object property value?

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.

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); 

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. :)

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'])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM