【问题标题】:How to compare two array and mismatch based on index using javascript?如何使用javascript根据索引比较两个数组和不匹配?
【发布时间】:2022-12-18 14:47:24
【问题描述】:
var a=["a","b","c","d"];
var b=["b","a","c","d"];

我需要这样的输出:

来自 a 的不匹配数组

不匹配数组=["a", "b"];

【问题讨论】:

标签: javascript jquery


【解决方案1】:

要比较两个数组并根据索引识别不匹配项,您可以使用 for 循环遍历每个数组中的元素。在每次迭代中,您可以检查当前索引处的元素是否不相等,如果不相等,则可以将它们添加到新数组中。这是一个例子:

var a = ["a", "b", "c", "d"];
var b = ["b", "a", "c", "d"];

// Create an empty array to hold the mismatched elements
var mismatch = [];

// Loop through the elements in the arrays
for (var i = 0; i < a.length; i++) {
  // Check if the elements at the current index are not equal
  if (a[i] !== b[i]) {
    // If they're not equal, add them to the mismatch array
    mismatch.push(a[i]);
    mismatch.push(b[i]);
  }
}

// Output the mismatch array
console.log("Mismatch array:", mismatch);

【讨论】:

    【解决方案2】:

    您可以使用过滤函数并使用数组中的索引检查值,然后您可以从 a 中获取不匹配的值。

    var a = ["a", "b", "c", "d"];
    var b = ["b", "a", "c", "d"];
    
    var c = a.filter(function (item, index) {
      return item !== b[index];
    });
    
    console.log(c);

    【讨论】:

      【解决方案3】:

      这里我使用了 Javascript 的 filter 方法来获取不匹配的 Array。

      const a = ["a","b","c","d"];
      const b = ["b","a","c","d"];
      
      const mismatchedArr = a.filter((aItem,index) => aItem !== b[index]);
      console.log(mismatchedArr); //Prints ["a","b"]
      

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 2015-09-03
        • 2017-09-30
        相关资源
        最近更新 更多