Count each strings occurrence in array of strings in JavaScript

Implement a function in JavaScript that given an array of strings representing the domains, counts the number of occurrences of each string as a substring in the whole array and returns it.

Input:
const URLs = [
  "www.google.com",
  "www.learnersbucket.com",
  "google.com",
  "learnersbucket.com",
  "news.learnersbucket.com",
];

Output:
{
  "www.google.com": 1,
  "www.learnersbucket.com": 1,
  "google.com": 2,
  "learnersbucket.com": 3,
  "news.learnersbucket.com": 1
}

We can solve this problem by using the Array.reduce() and String.includes().

  • Iterate all the strings and check if the current string is a substring of any other string in the array.
  • Count the number of occurrences and then store the count on the string in the result object.
const aggregate = URLs.reduce((acc, currStr, index, array) => {
 // to track the count of occurrences of the current string 
 let count = 0;
 
 // check if the current string is a substring 
 // of any of the strings in the given URL array
 // use the Boolean method to convert the boolean value to numerical.
 // 1 for true and 0 for false
 array.forEach((url) => (count += Boolean(url.includes(currStr))));
 
 // update the count for the string
 acc[currStr] = count;
  
 // return the object
 return acc;
}, {});
Input:
const URLs = [
  "www.google.com",
  "www.learnersbucket.com",
  "xyz.www.google.com",
  "abc.xyz.www.google.com",
  "google.com",
  "learnersbucket.com",
  "practice.learnersbucket.com",
  "abc.news.learnersbucket.com",
  "abc.xyz.www.google.com",
  "www.learnersbucket.com",
  "google.com",
];

console.log(aggregate);

Output:
{
  "www.google.com": 4,
  "www.learnersbucket.com": 2,
  "xyz.www.google.com": 3,
  "abc.xyz.www.google.com": 2,
  "google.com": 6,
  "learnersbucket.com": 5,
  "practice.learnersbucket.com": 1,
  "abc.news.learnersbucket.com": 1
}