group array and get count

前端 未结 6 486
执念已碎
执念已碎 2021-01-12 07:00

Say I have array like this:

[
   \"foo\",
   \"bar\",
   \"foo\"
   \"bar\",
   \"bar\",
   \"bar\",
   \"zoom\"
]

I want to group it so I

6条回答
  •  青春惊慌失措
    2021-01-12 07:52

    You could use the reduce() method which is avalible on the array object to achieve this grouping. So, something along the lines of this might achieve what you're after:

        var input = [
           "foo",
           "bar",
           "foo",
           "bar",
           "bar",
           "bar",
           "zoom"
        ]
        
        // Iterate the input list and construct a grouping via a "reducer"
        var output = input.reduce(function(grouping, item) {
        
          // If the current list item does not yet exist in grouping, set 
          // it's initial count to 1
          if( grouping[item] === undefined ) {    
            grouping[item] = 1;
          }
          // If current list item does exist in grouping, increment the 
          // count
          else {
            grouping[item] ++;
          }
        
          return grouping;
        
        }, {})
        
        console.log(output)

提交回复
热议问题