使用JavaScript从多个数组中检索公共值

时间:2017-11-04 08:42:58

标签: javascript typescript

从给定数组

中检索公共值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]

3 个答案:

答案 0 :(得分:2)

您可以将Array#reduceArray#filterArray#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)]);