skip to Main Content
const obj1 = {
  1: 'a',
  2: 'b',
  3: 'a',
  4: 'c',
  5: 'a',
  6: 'd',
  7: 'c',
};

For the above code I need to get output as below

output = { a: 3, b:  1, c: 2, d: 1 }

2

Answers


  1. this function works

    function countOccurrences(obj) {
      const result = {};
    
      for (const key in obj) {
        const value = obj[key];
        result[value] = (result[value] || 0) + 1;
      }
      return result;
    }
    // Input object
    const obj1 = {
      1: 'a',
      2: 'b',
      3: 'a',
      4: 'c',
      5: 'a',
      6: 'd',
      7: 'c'
    };
    
    // Call the function
    const output = countOccurrences(obj1);
    console.log(output); // Output: { a: 3, b: 1, c: 2, d: 1 }
    Login or Signup to reply.
  2. A concise / advanced solution would look like this:

    Object.values(obj1).reduce((o,n)=>{
        if (!o[n]) o[n]=0;
        o[n]+=1;
        return o;
    }, {})
    

    Object.values() gives you the values of an object (see documentation).

    Array.protoype.reduce() is a function which takes a function as its argument. Because we want to start on an empty object, we give it {} as a second input parameter. The reduce function iterates over all given array values and applying the given function to it. The result is a single value opposed to what Array.prototype.map does.
    (see documentation)

    For read-/memorability reasons I choose the parameter names o for old and n for new for the reduce function.
    What we are doing here is simple:

    • look whether on the given "old" value (which is in the first step {}) exists a key of n (n is a in the first step). If not give it a count of 0.
    • anyways increase the count at o[n].
    • return o

    As you see the o is passed in and back the function and it accumulates the count. So this part is often called accumulator. But I use o because old is easier for me to remember than accumulator.

    Functions like Array.prototype.map and Array.protoype.reduce ( and don’t forget Array.protoype.reduceRight) are hard to understand at first. But once understood they will be the best tools on your belt.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search