Scan array via javascript and remove duplicate objects with Map

Asked

Viewed 851 times

0

I’m going through the following JSON:

[
    {
        "amount": 6,
        "codes": [
            "BRCH",
            "ARSI",
            "ENSI"
        ]
    },
    {
        "amount": 6,
        "codes": [
            "BRCH",
            "ARSI",
            "ENSI"
        ]
    },
        {
        "amount": 6,
        "codes": [
            "BRCH",
            "ARSI",
            "ENSI"
        ]
    },
    {
        "amount": 2,
        "codes": [
            "BRSI",
            "ARSI"
        ]
    },
        {
        "amount": 2,
        "codes": [
            "BRSI",
            "ARSI"
        ]
    }
]

Well, I am using the javascript Map function to go through it and remove the repeated items and for that I check if the quantity and codes are equal:

let unique = new Map(itemsToClear.map(obj => [obj.amount, obj] && [obj.options.codes, obj]));
const uniques = Array.from(unique.values());

However, by using this form it is not able to scan the code array, there is a way to perform this action?

  • 4

    "because it contains a lot of junk and unnecessary data", that’s an excellent sign that you should craft a [mcve] eliminating all that noise.

  • Thanks for the tip! I updated the question Minimalizando to be clearer.

  • if you want to remove duplicates could create a new array only with single items, adding the items within the map, that such?

  • How could I mount it then? I’m trying to accomplish this even with the Array.from function

1 answer

1


You can compare whether 2 objects "are equal" convert both to a JSON string.

const array = [
    {
        "amount": 6,
        "codes": ["BRCH", "ARSI", "ENSI"]
    },
    {
        "amount": 6,
        "codes": ["BRCH", "ARSI", "ENSI"]
    },
    {
        "amount": 6,
        "codes": ["BRCH", "ARSI", "ENSI"]
    },
    {
        "amount": 2,
        "codes": ["BRSI", "ARSI"]
    },
    {
        "amount": 2,
        "codes": ["BRSI", "ARSI"]
    }
];

const result = array
    .map(e => JSON.stringify(e))
    .reduce((acc, cur) => (acc.includes(cur) || acc.push(cur), acc), [])
    .map(e => JSON.parse(e));

console.log(result);

  • 2

    I don’t think I use JSON.stringify for this type of use is something safe, since if the order of the keys is changed, the comparison will be wrong. See here. I might even use the Array.prototype.sort, but I think it would only create additional complexity...

  • @Luizfelipe uses method includes()... order does not matter...

  • The order is taken into account yes, since you are checking whether the whole object (in the form of string) already exists. As the output in string varies, according to the order of the properties, the filtering is impaired. Look in the Repl.it.

  • @Luizfelipe right, had not even seen the link, I was not thinking of that order...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.