开发者

How to compare two array and mismatch based on index using javascript? [duplicate]

This question already has answers here: How to compare two arrays and then return the index of the difference? (4 answers) How to get the difference between two arrays in JavaScript? (83 answers) Javascript compare 2 arrays index by index, and not by total number of values the 2 arrays have in common 开发者_如何转开发 (2 answers) Closed 6 hours ago.
var a=["a","b","c","d"];
var b=["b","a","c","d"];

I need output like:

mismatched array from a

mismatch array=["a", "b"];


You can use filter function and check value with the index in both the array and then you can get the mismatched values from 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);


Here I used Javascript's filter method to get the mismatched 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"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜