-1

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]];
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • Why sub arrays like that? Why not something like `[{letter: "a", count: 3}, {letter: "b"...} ...]`? – TKoL Nov 01 '17 at 12:08
  • 1
    Possible duplicate of [How to count duplicate value in an array in javascript](https://stackoverflow.com/questions/19395257/how-to-count-duplicate-value-in-an-array-in-javascript) – Durga Nov 01 '17 at 12:09
  • no it is not duplicate in above question array is not converting into sub arrays. – user2778724 Nov 01 '17 at 13:30

3 Answers3

3

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 1
    Nice!!, seen as your using ES6, an arrow function would make it look even nicer. `var result = [...myArray.reduce((r, e) => r.set(e, !r.get(e) ? 1 : r.get(e) + 1), new Map())]` – Keith Nov 01 '17 at 13:18
  • thanks it works perfectly @nenad – user2778724 Nov 01 '17 at 13:26
0

If you want solution in your way than try it

var myArray=["a","b","c","a","a","c","b"];
var obj = [];
for (var i = 0, j = myArray.length; i < j; i++) {
   obj[myArray[i]] = (obj[myArray[i]] || 0) + 1;
}
var finalArr = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        var arr = [];
        arr.push(key);
        arr.push(obj[key]);
        finalArr.push(arr);
    }
}
console.log(finalArr);
Durga
  • 15,263
  • 2
  • 28
  • 52
bipin patel
  • 2,061
  • 1
  • 13
  • 22
-1
function countLetters(arr) {
    return arr.reduce(function(r, e) {
        r[e] = (r[e] || 0) + 1;
        return r;
    }, {});
}

An alternative method

GApple
  • 11
  • 3
  • You should answer the question the way the user wants and then give your input and alternative method after. I didn't down vote but most likely whomever did, that is why. – Matt Nov 01 '17 at 12:30