Home > front end >  How to get quantity of duplicates in array nodejs
How to get quantity of duplicates in array nodejs

Time:08-19

I'm trying to get the quantity of for example: DragonBall, it would return x3 or Featured it would return x2 etc, however I have tried this method with just the spammed response of 2

let data = mockdata.forEach(function (i) {
      count[i] = (count[i] || 0)   1;
      console.log(count[i] = (count[i] || 0)   1)
});
[
  'Daily',
  'DragonBall1B',
  'DragonBall2B',
  'DragonBall3B',
  'Featured',
  'Featured2',
  'SquadOrigins',
  'SquadOrigins2'
]

API used to retrieve the above information: https://fortnitecontent-website-prod07.ol.epicgames.com/content/api/pages/fortnite-game/shop-sections

CodePudding user response:

A regular expression can remove the first instance of digits (along with whatever follows) to get you to the key you're interested in grouping on.

const mockdata = [
  'Daily',
  'DragonBall1B',
  'DragonBall2B',
  'DragonBall3B',
  'Featured',
  'Featured2',
  'SquadOrigins',
  'SquadOrigins2'
]
const count = {};
mockdata.forEach((str) => {
  const key = str.replace(/\d .*/, '');
  count[key] = (count[key] || 0)   1;
});
console.log(count.DragonBall);

CodePudding user response:

const arr = [
  'Daily',
  'DragonBall1B',
  'DragonBall2B',
  'DragonBall3B',
  'Featured',
  'Featured2',
  'SquadOrigins',
  'SquadOrigins2'
]
const count = {};
arr.forEach((str) => {
        const key = str.replace(/\d .*/, "");
        count[key] = (count[key] || 0)   1;
      });
      let val = Object.entries(count);
      let itemName;
      let itemNum;
      let result = [];
      for (var i in val) {
        itemName = val[i][0];
        itemNum = val[i][1];
        result  = `${itemName} (x${itemNum})\n`;
      }
       console.log(result);

CodePudding user response:

This should be the most efficent

const arr = [
  'Daily',
  'DragonBall1B',
  'DragonBall2B',
  'DragonBall3B',
  'Featured',
  'Featured2',
  'SquadOrigins',
  'SquadOrigins2'
]

const map = new Map()
arr.forEach(e => map.set(e, (map.get(e) || 0)   1))
  • Related