Is there a Javascript function similar to the Python Counter function?

前端 未结 6 2200
逝去的感伤
逝去的感伤 2021-02-19 01:17

I am attempting to change a program of mine from Python to Javascript and I was wondering if there was a JS function like the Counter function from the collections module in Pyt

6条回答
  •  鱼传尺愫
    2021-02-19 02:04

    I know I'm late but in case if someone is looking at this in 2020 you can do it using reduce, for example:

    const counter = (list) => {
      return list.reduce(
        (prev, curr) => ({
          ...prev,
          [curr]: 1 + (prev[curr] || 0),
        }),
        {}
      );
    };
    
    console.log(counter([1, 2, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 1, 0]));
    // output -> { '0': 1, '1': 6, '2': 2, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1 }
    

    more advance example with a callback function and context binding

    const data = [1, 2, 3, 4, 5];
    
    const counter = (list, fun, context) => {
      fun = context ? fun.bind(context) : fun;
      return list.reduce((prev, curr) => {
        const key = fun(curr);
        return {
          ...prev,
          [key]: 1 + (prev[key] || 0),
        };
      }, {});
    };
    
    
    console.log(counter(data, (num) => (num % 2 == 0 ? 'even' : 'odd')));
    // output -> { odd: 3, even: 2 }
    

提交回复
热议问题