DEV Community

Miguel Ramirez
Miguel Ramirez

Posted on

typescript - using reduce to get repited items

const listItems = ["papa", "camote", "yuca", "papa"];

const result =  listItems.reduce((acc,current: string) => {
    acc[current] = acc[current] ? acc[current] + 1 : 1;
    return acc;
}, {} as any);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

example response:

[LOG]: {
  "papa": 2,
  "camote": 1,
  "yuca": 1
} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)