【问题标题】:Retrieve the common values from multiple array using JavaScript [closed]使用 JavaScript 从多个数组中检索公共值 [关闭]
【发布时间】:2018-04-16 23:11:22
【问题描述】:

从给定数组中检索公共值 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]

【问题讨论】:

  • Please solve my problem ?? SO 不是编码服务。你试过了吗?
  • 是的,我从早上开始就在尝试这个棘手的问题。你能解决这个问题吗?
  • “你能解决这个问题吗?” 不用了,我今天很懒……
  • 为什么不发布您尝试过的内容,我们可以尝试帮助您
  • 请参阅How to Ask 链接以获取有关如何提出问题并相应更新您的问题的更多详细信息。

标签: javascript typescript


【解决方案1】:

您可以将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);

【讨论】:

  • 谢谢你尼娜 :-)
【解决方案2】:

最基本的做法应该是这样的:

伪代码:

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]

您基本上需要从公共数组中删除检查数组中不存在的每个元素。这样做 n 次将导致 commonArray 的元素在所有数组中都是通用的。

【讨论】:

    【解决方案3】:

    您可以将数组展平,然后使用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)]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      相关资源
      最近更新 更多