0

I have array of objects that look like:

{
  "brandid": id,
  "brand": string,
  "id": id,
  "categoryId": id,
  "category": string,
  "factory": string,
  "series": string,
  "status": 0,
  "subStatus": 1
}

if the series property value matches another series property value in the other objects in the array, that object needs to be removed from the array.

Currently I have attempted to push them to a duplicate Array with :

      const seriesResCopy = seriesRes;
      const dupArray = []
      for (const thing of seriesResCopy) {
        for (const item of seriesRes) {
          if (thing.series === item.series) {
            dupArray.push(item);
          }
        }
      }

but this does not work. From examples I have seem my issue has been that I do not have a definite list of duplicate values to look for.

Any help would be much appreciated.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Brian Stanley
  • 2,078
  • 5
  • 24
  • 43

2 Answers2

4

You could use a Set of series to filter out duplicates:

const exists = new Set();
seriesRes = seriesRes.filter(({series}) => !exists.has(series) && exists.add(series));

This uses: Array.prototype.filter, Object destructuring and some logical tricks.

The same can be done by mutating the array:

const exists = new Set();
for(const [index, {series}] of seriesRes.entries()) {
  if(!exists.has(series) {
    exists.add(series);
  } else {
    seriesRes.splice(index, 1);
  }
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Please do explode the code and comment what it does. It is very elegant but very new (as of June 2018) too – mplungjan Jun 08 '18 at 18:12
  • fantastic idea with set, i have used it [lately](https://stackoverflow.com/a/40482611/1447675), or later or so. – Nina Scholz Jun 08 '18 at 18:25
  • @mplungjan if you change the question, why should the answers still fit?!? – Jonas Wilms Jun 09 '18 at 09:16
  • @mplungjan the OP has accepted this answer. So if you say "this does not work for my weird snippet i made out of the OPs code" then this is a fault on your side, not my's. – Jonas Wilms Jun 09 '18 at 12:55
  • Your code is interesting. So how does the object need to look like to work with your code? Ops original object was not complete or valid and I just tried to male a [mcve] out of it. Why do hostile? – mplungjan Jun 09 '18 at 12:58
  • 1
    It would not be the first time an asker posted an object and called it an array. So all I had to do was to wrap in []. That would have been useful if OP had shown a valid array in my opinion. So not so weird. Anyway your code is still interesting – mplungjan Jun 09 '18 at 13:52
0

To filter duplicates from the array and keep the first instance:

let seriesWithoutDuplicates = seriesRes.filter((s, i, self) => {
    return self.findIndex(z => z.series === s.series) === i;
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157