Skip to content Skip to sidebar Skip to footer

Get Duplicates In Array Of Strings And Count Number Of Duplicates

What's the best way to get duplicates in an array of hashes with strings and count number of appearances. If I have this array of hashes const data = [ { url: 'https://app.my

Solution 1:

You can use Array.reduce for that :

const data = [
  {
    url: "https://app.mywebsite.net/endpoint1",
    method: "POST"
  },
  {
    url: "https://app.mywebsite.net/endpoint2",
    method: "POST"
  },
  {
    url: "https://app.mywebsite.net/endpoint1",
    method: "POST"
  }
];

const result = data.reduce((all, curr) => {
  const ndx = all.findIndex(e => e.url === curr.url);

  if (ndx > -1) {
    all[ndx].count += 1;
  } else {
    all.push({ url: curr.url, count: 1 });
  }

  return all;
}, []);


console.log(result)

Solution 2:

Like @Taki mentions, you can use the Array.prototype.reduce() method.

const frequencies = arr =>
  Object.values(
    arr.reduce((obj, { url, method }) => {
      obj[url] = obj[url] || { url, method, count: 0 }
      obj[url].count += 1
      return obj
    }, {})
  )

const data = [
  {
    url: 'https://app.mywebsite.net/endpoint1',
    method: 'POST',
  },
  {
    url: 'https://app.mywebsite.net/endpoint2',
    method: 'POST',
  },
  {
    url: 'https://app.mywebsite.net/endpoint1',
    method: 'POST',
  },
]

const result = frequencies(data)

console.log(result)

Solution 3:

Using with reduce (or forEach) will simplify.

const data = [
  {
    url: "https://app.mywebsite.net/endpoint1",
    method: "POST"
  },
  {
    url: "https://app.mywebsite.net/endpoint2",
    method: "POST"
  },
  {
    url: "https://app.mywebsite.net/endpoint1",
    method: "POST"
  }
];

const updated = data.reduce(
  (acc, curr) =>
    Object.assign(acc, {
      [curr.url]:
        curr.url in acc
          ? { ...acc[curr.url], count: acc[curr.url].count + 1 }
          : { ...curr, count: 1 }
    }),
  {}
);

console.log(updated);

Post a Comment for "Get Duplicates In Array Of Strings And Count Number Of Duplicates"