Let’s say the following is our first array −
const firstArray = [ { "name": "John Doe" }, { "name": "John Smith" }, { "name": "David Miller" }, { "name": "Bob Taylor" }, { "name": "Carol taylor" }, { "name": "Adam Smith" }, ];
Let’s say the following is our second array −
const secondArray = [ { "name": "Adam Smith" }, { "name": "John Doe" }, { "name": "David Miller" }, { "name": "James Taylor" } ];
To compare, use map() and includes().
Example
Following is the code −
const firstArray = [ { "name": "John Doe" }, { "name": "John Smith" }, { "name": "David Miller" }, { "name": "Bob Taylor" }, { "name": "Carol taylor" }, { "name": "Adam Smith" }, ]; const secondArray = [ { "name": "Adam Smith" }, { "name": "John Doe" }, { "name": "David Miller" }, { "name": "James Taylor" } ]; const getAllValue = ({ 'name': name }) => name; const result = firstArray .map(getAllValue) .filter(value => secondArray .map(getAllValue) .includes(value) ); console.log(result);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo251.js
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo251.js [ 'John Doe', 'David Miller', 'Adam Smith' ]