从给定数组
中检索公共值12示例: 输入,如:
[ [12, 6],[12, 11, 9, 8, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1],[12, 11, 9, 8, 6, 1] ]
我的预期输出为:
[12]
答案 0 :(得分:2)
您可以将Array#reduce
与Array#filter
和Array#includes
一起使用。
var array = [[12, 6], [12, 11, 9, 8, 1], [12, 11, 9, 8, 6, 1], [12, 11, 9, 8, 6, 1], [12, 11, 9, 8, 6, 1]],
result = array.reduce((a, b) => a.filter(c => b.includes(c)));
console.log(result);
答案 1 :(得分:0)
最基本的方法应如下:
<强>伪代码:强>
commonArray = clone(allArrays[0])
for i in 1, length(allArrays) do:
removeIfNotExists(initialArray, allArrays[i])
removeIfNotExists可以有如下逻辑:
removeIfNotExists(commonArray, checkArray):
for(index in commonArray):
if(commonArray[index] not in checkArray):
delete commonArray[index]
您基本上需要删除check数组中不存在的公共数组中的每个元素。这样做n次将导致commonArray具有在所有数组中通用的元素。
答案 2 :(得分:0)
你可以压扁阵列&amp;然后使用reduce
方法计算每个项目的出现次数。然后遍历该对象并使用具有最高出现次数的元素更新变量。
var x = [
[12, 6],
[12, 11, 9, 8, 1],
[12, 11, 9, 8, 6, 1],
[12, 11, 9, 8, 6, 1],
[12, 11, 9, 8, 6, 1]
]
// flattening the array and reducing to single object
var flatObj = [].concat.apply([], x).reduce(function(a, b) {
// the object have same key update the count or add a new key
a[b] = "undefined" == typeof a[b] ? 1 : a[b] + 1;
return a;
}, Object.create(null)),
highestValue = 0,
num, keys;
//looping through the newly created object
for (keys in flatObj) {
updating variable with the values
flatObj[keys] > highestValue && (highestValue = flatObj[keys], num = keys);
}
console.log([Number(num)]);