Unique Solution
An innovative algorithm could consist of the following three steps:
- Calculating the frequency of each element in every subarray of a two-dimensional array.
- Constructing a new two-dimensional array to group elements with the same frequency together.
- Arranging the subarrays of the new 2D array in descending order based on the common frequency shared by their elements within the original array.
Note: To account for non-consecutive frequencies, this new 2D array is initially represented as a sparse object before being converted into a dense array in the JavaScript implementation provided below:
function mostCommon(a) {
var byFrequency = [], keyCount = {}, byCount = {}, k;
/* Step 1 */
a.map(function(x) {
x.map(function(y) {
if (!keyCount[y]) keyCount[y] = 1;
else keyCount[y]++;
});
});
/* Step 2 */
for (k in keyCount) {
if (!byCount[keyCount[k]])
byCount[keyCount[k]] = [], byFrequency[byFrequency.length] = keyCount[k];
byCount[keyCount[k]].push(k);
}
/* Step 3 */
byFrequency.sort(function(a,b) { return b-a; });
return byFrequency.map(function(x) { return byCount[x]; });
}
var arr = [
["one", "two", "three", "four", "five"] ,
["one", "two", "three", "six", "seven"] ,
["one", "two", "eight", "four", "ten"]
/* Additional rows (arrays) can be included */
];
console.log(JSON.stringify(mostCommon(arr)));
/* [["one","two"],["three","four"],["five","six","seven","eight","ten"]] */
Updated Approach
If there is a need to handle individual elements separately from grouped ones, it's straightforward to split the final array returned accordingly. An updated version of the function includes an optional flag for this purpose, along with conditional statements for handling special cases:
function mostCommon(a, optSplitSingle) {
var byFrequency = [], keyCount = {}, byCount = {}, i, k;
a.map(function(x) {
x.map(function(y) {
if (!keyCount[y]) keyCount[y] = 1;
else keyCount[y]++;
});
});
for (k in keyCount) {
if (!byCount[keyCount[k]]) {
byCount[keyCount[k]] = [];
byFrequency[byFrequency.length] = keyCount[k];
}
byCount[keyCount[k]].push(k);
}
byFrequency.sort(function(a,b) { return b-a; });
a = byFrequency.map(function(x) { return byCount[x]; });
if (optSplitSingle && byCount[1]) {
for (k=a.length-1, i=0; i<byCount[1].length; i++)
a[k++] = byCount[1][i];
}
return a;
}
var arr = [
["one", "two", "three", "four", "five"] ,
["one", "two", "three", "six", "seven"] ,
["one", "two", "eight", "four", "ten"]
/* More rows (arrays) can be added */
];
console.log(JSON.stringify(mostCommon(arr, true)));
/* [["one","two"],["three","four"],"five","six","seven","eight","ten"] */