Chopra Chopra - 19 days ago 7
Javascript Question

sort by number of occurrence(count) in Javascript array

I am new to Jquery and Javascript. Can someone please help me with Jquery sorting based on number of occurrence(count) in array. I tried various sorting methods but none of them worked.

I have an array in Javascript which is

allTypesArray = ["4", "4","2", "2", "2", "6", "2", "6", "6"]

// here 2 is printed four times, 6 is printed thrice, and 4 is printed twice


I need output like this

newTypesArray = ["2","6","4"]


I tried

function array_count_values(e) {
var t = {}, n = "",
r = "";
var i = function (e) {
var t = typeof e;
t = t.toLowerCase();
if (t === "object") {
t = "array"
}
return t
};
var s = function (e) {
switch (typeof e) {
case "number":
if (Math.floor(e) !== e) {
return
};
case "string":
if (e in this && this.hasOwnProperty(e)) {
++this[e]
} else {
this[e] = 1
}
}
};
r = i(e);
if (r === "array") {
for (n in e) {
if (e.hasOwnProperty(n)) {
s.call(t, e[n])
}
}
}
return t
}
6: 3
}


output is
{4: 2, 2: 6, 6:3}

Answer

Just adding my idea as well (a bit too late)

var allTypesArray = ["4", "4", "2", "2", "2", "6", "2", "6", "6"];
var map = allTypesArray.reduce(function (p, c) {
    p[c] = (p[c] || 0) + 1;
    return p;
}, {});
var newTypesArray = Object.keys(map).sort(function (a, b) {
    return map[a] < map[b];
});
Comments