skip to Main Content

I have this set of array in my javascript.

var array = [
['Jack', 'A'], 
['Jack', 'A'], 
['Sara', 'A'], 
['Jack', 'B'], 
['Peter', 'B'],
['Sara', 'C'], 
['Sara', 'B'],
['Sara', 'A'],
['Sara', 'B'], 
['Peter', 'B'],
['Peter', 'A'],
['Peter', 'C']
];

my goal is to be arranged like this as an array.

Jack: A : 2
Jack: B : 1
Sara: A : 2
Sara: B : 2
Sara: C : 1
Peter: A : 1
Peter: B : 2
Peter: C : 1

I am trying to code it like this but I can’t get it right

let counts = {};
array.forEach(element => {
     counts[element] = (counts[element] || 0) + 1;
});

does anyone has an idea about this one?
Thank you..

2

Answers


  1. I think you want something like this:

    let array = [
            ['Jack', 'A'], 
            ['Jack', 'A'], 
            ['Sara', 'A'], 
            ['Jack', 'B'], 
            ['Peter', 'B'],
            ['Sara', 'C'], 
            ['Sara', 'B'],
            ['Sara', 'A'],
            ['Sara', 'B'], 
            ['Peter', 'B'],
            ['Peter', 'A'],
            ['Peter', 'C']
        ];
    
        function transformArray(arr)
        {
            let result = {};
    
            arr.forEach(function(item) {
    
                let name = item[0];
    
                let category = item[1];
        
                if (!result[name]) {
                    result[name] = {};
                }
        
                if (!result[name][category]) {
                    result[name][category] = 1;
                } else {
                    result[name][category]++;
                }
            });
        
            return result;
        }
    
        console.log(transformArray(array));
    Login or Signup to reply.
  2. You could group by both values and map the count.

    const
        data = [['Jack', 'A'], ['Jack', 'A'], ['Sara', 'A'], ['Jack', 'B'], ['Peter', 'B'], ['Sara', 'C'], ['Sara', 'B'], ['Sara', 'A'], ['Sara', 'B'], ['Peter', 'B'], ['Peter', 'A'], ['Peter', 'C']],
        result = Object
            .values(Object.groupBy(data, a => a.join('|')))
            .map(a => [...a[0], a.length]);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search