【问题标题】:Javascript compare 2 arrays index by index, and not by total number of values the 2 arrays have in commonJavascript 按索引比较 2 个数组,而不是按 2 个数组共有的值的总数
【发布时间】:2020-05-04 21:24:56
【问题描述】:

所以我有这段代码返回比较 2 个数组的结果。该函数比较两个数组有多少共同值,然后输出共同值的百分比。

const array1 = [1, 2, 3, 7, 1];
const array2 = [1, 3, 6, 7, 6];

const compareThem = (num1, num2) => {
  let finalArray = [];
  num1.forEach((e1) => num2.forEach((e2) => {
    if (e1 === e2) {
      finalArray.push(e1)
    }
  }))
  const divideThem = Math.floor((finalArray.length / num1.length) * 100)
  const toPercent = (divideThem.toFixed(1) + '%')
  return toPercent;

};
console.log(compareThem(array1, array2))

但我想做一些不同的事情。我想按索引进行索引,并让代码说 array1[0] === array2[0], [1] === [1] 等等。我不是在寻找共有值的总数,而是它们共有的索引总数。我不希望代码说 array1[1] === array2[3]。 解决这个问题的最佳方法是什么?我想首先我将不得不使用除 foreach 以外的其他东西?

【问题讨论】:

  • forEach 回调函数获取第二个参数,即数组索引。您可以使用它与另一个数组中的相同索引进行比较。
  • 这是一个很好奇的问题,因为你想要做的其实比上面的代码要容易得多。
  • @Barmar 但这不会只返回它们有多少共同索引吗?与比较索引处的值相反。所以说 array1[1] = 5 和 array2[1] 也 = 5
  • 另外,您的预期输出是什么样的?你已经提到了你不希望它是什么,但没有说你实际上想要什么结果。您是否在使用一系列布尔值:[true, false, false, true, false]
  • @NickParsons 我希望它返回一个共有值的数组。这样,最终数组的长度可以除以 array1 的长度以返回一个小数,该小数转换为百分比,该百分比将是有多少索引具有相同的值

标签: javascript arrays foreach iterator


【解决方案1】:

只需将e1 与另一个数组中具有相同索引的元素进行比较。所有数组迭代函数都将索引作为参数传递给回调。

如果您只需要计数,则无需推入数组。您可以使用reduce() 计算匹配的总数。

const array1 = [1, 2, 3, 7, 1];
const array2 = [1, 3, 6, 7, 6];

const compareThem = (num1, num2) => {
  let counter = num1.reduce((total, e1, index) => e1 === num2[index] ? total + 1: total, 0)
  const divideThem = Math.floor((counter / num1.length) * 100)
  const toPercent = (divideThem.toFixed(1) + '%')
  return toPercent;

};
console.log(compareThem(array1, array2))

【讨论】:

    【解决方案2】:

    回调函数接收到第二个参数,即索引。您可以使用该索引将值与第二个数组的值进行比较。

    最终结果会是这样的

    const compareThem = (a1, a2) => {
      let commonIndices = [];
      a1.forEach((element, i) => {
        if (element === a2[i]) {
          commonIndices.push(element)
        }
      });
      return commonIndices;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      相关资源
      最近更新 更多