我们需要编写一个JavaScript函数,该函数接受任意数量的数字数组。然后,该函数应返回一个对象,该对象返回一个频率图,该频率图指示每个元素在所有数组中检查了多少次。
例如,如果数组是-
const a = [23, 45, 21], b = [45, 23], c = [21, 32], d = [23], e= [32], f=[50, 54];
那么输出应该是-
const output = {
"21": 2,
"23": 3,
"32": 2,
"45": 2,
"52": 1,
"54": 1,
"23, 45": 2,
"23, 45, 21": 1,
"21, 32": 1,
"50 : 54": 1,
"50" : 1
}为此的代码将是-
const a = [23, 45, 21], b = [45, 23], c = [21, 32], d = [23], e= [32], f=[50, 54];
const findMatch = arr => {
let result = [];
const pick = (i, t) => {
if (i === arr.length) {
t.length && result.push(t);
return;
};
pick(i + 1, t.concat(arr[i]));
pick(i + 1, t);
};
pick(0, []);
return result;
};
const sorter = (a, b) => a - b;
const mergeCombination = (arr, obj) => {
findMatch(arr.sort(sorter)).forEach(el => {
return obj[el.join(', ')] = (obj[el.join(', ')] || 0) + 1
});
};
const buildFinalCombinations = (...arrs) => {
const obj = {};
for(let i = 0; i < arrs.length; i++){
mergeCombination(arrs[i], obj);
};
return obj;
};
console.log(buildFinalCombinations(a, b, c, d, e, f));输出结果
控制台中的输出-
{
'21': 2,
'23': 3,
'32': 2,
'45': 2,
'50': 1,
'54': 1,
'21, 23, 45': 1,
'21, 23': 1,
'21, 45': 1,
'23, 45': 2,
'21, 32': 1,
'50, 54': 1
}