Search code examples
javascriptarraysloopsobjectreduce

Given an array of strings, write a function that returns an array of objects representing each unique string and its frequency in the original array


I want to print the string and the frequency of it as an object stored inside an array. I have been using only reduce method to do so and want result through the same method only, Can anyone tell me what should I rectify in the below code:

const strings = ["pink", "red", "pink", "yellow", "yellow", "yellow"];

const frequencyOfStrings = (arrayOfStrings) => {
  return arrayOfStrings.reduce((acc, curr) => {
    if (acc[curr]) {
      acc[curr]++;
    } else {
      acc[curr] = 1;
    }
    return acc;
  }, []);
};

console.log(frequencyOfStrings(strings));

I am getting output as:

[ pink: 2, red: 1, yellow: 3 ]

Whereas I want my output as:

[{ string: 'pink', frequency: 2 }, { string: 'red', frequency: 1 }, { string: 'yellow', frequency: 3 }]

P.S - I am a beginner at Javascript with no knowledge of time-complexities, as of now.


Solution

  • To achieve the desired output format, you need to modify the reduce function to return an array of objects instead of an object. Here is the updated code

    const strings = ["pink", "red", "pink", "yellow", "yellow", "yellow"];
    
    const frequencyOfStrings = (arrayOfStrings) => {
      return Object.entries(
        arrayOfStrings.reduce((acc, curr) => {
          if (acc[curr]) {
            acc[curr]++;
          } else {
            acc[curr] = 1;
          }
          return acc;
        }, {})
      ).map(([string, frequency]) => ({ string, frequency }));
    };
    
    console.log(frequencyOfStrings(strings));