Search code examples
javascriptjqueryarrayssub-array

Convert array to sub arrays based on their count in JavaScript/jQuery?


How can I convert my array to sub arrays depending upon their elements values counts in JavaScript or jQuery?

For example:

var myArray=["a","b","c","a","a","c","b"];

Expected output after counting the elements a, b and c

outputArray=[["a",3],["b",2],["c",2]];

Solution

  • You could use reduce() and ES6 Map() and spread syntax ....

    var myArray=["a","b","c","a","a","c","b"];
    
    var result = [...myArray.reduce(function(r, e) {
      return r.set(e, !r.get(e) ? 1 : r.get(e) + 1)
    }, new Map())]
    
    console.log(result)