search

Home  >  Q&A  >  body text

javascript - Looking for the most elegant way to process data?

Given the endorsement array, it is required to write a function to achieve the desired output result:

// function input 
var endorsements = [ 
{ skill: 'javascript', user: 'Chad' }, 
{ skill: 'javascript', user: 'Bill' }, 
{ skill: 'javascript', user: 'Sue' }, 
{ skill: 'html', user: 'Sue' }, 
{ skill: 'css', user: 'Sue' }, 
{ skill: 'css', user: 'Bill' } 
]; 

// function output 
[ 
{ skill: 'javascript', user: [ 'Chad', 'Bill', 'Sue' ], count: 3 }, 
{ skill: 'css', user: [ 'Sue', 'Bill' ], count: 2 }, 
{ skill: 'html', user: [ 'Sue' ], count: 1 } 
];
PHPzPHPz2792 days ago486

reply all(1)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:25:13

    let output = []
    
    endorsements.reduce((dict, item) => {
      if (!dict[item.skill]) {
        dict[item.skill] = {
          skill: item.skill,
          user: [item.user],
          count: 1
        }
        output.push(dict[item.skill])
      } else {
        dict[item.skill].user.push(item.user)
        dict[item.skill].count += 1
      }
      return dict
    }, {})
    
    output = output.sort((a, b) => b.count - a.count)
    
    console.log(output)

    reply
    0
  • Cancelreply