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

I need output like:

mismatched array from a

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Sam
  • 1
  • 2
  • Welcome to SO. We encourage you to add any code you've attempted to solve this to your question as a [mcve]. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Andy Dec 07 '22 at 04:48
  • `const mismatch = a.reduce((acc,curr,i) => (curr != b[i] ? acc.push(curr) : 0, acc), [])` – Spectric Dec 07 '22 at 04:48
  • But also checkout [the documentation on loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration). – Andy Dec 07 '22 at 04:48
  • Possible duplicate of : [How to get the difference between two arrays in JavaScript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – Alive to die - Anant Dec 07 '22 at 04:51
  • Please add the code you have tried. A simple `for` loop with a comparison between `a[i]` with `b[i]` and adding it to ouptut array should work. – adiga Dec 07 '22 at 06:13

2 Answers2

0

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);
DCodeMania
  • 1,027
  • 2
  • 7
  • 19
0

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"]
Vinay N
  • 249
  • 1
  • 8
  • 32