-1

I have two arrays:

[
  {
    login: "LoginAAA",
    url: "someurl-aaa",
    number: 23
  },
  {
    login: "LoginBBB",
    url: "someurl-bbb",
    number: 56
  },
  {
    login: "LoginCCC",
    url: "someurl-ccc",
    number: 12
  },
    {
    login: "LoginDDD",
    url: "someurl-ddd",
    number: 45
  }
 ]

and

 [
  {
    login: "LoginAAA",
    url: "someurl-aaa",
    number: 23
  },
  {
    login: "LoginDDD",
    url: "someurl-ddd",
    number: 45
  },
    {
    login: "LoginZZZ",
    url: "someurl-zzz",
    number: 53
  }
 ]     

Now, I need to compare arrays and filter those arrays and leave only repeated elements by one key e.g "login".

[
  {
    login: "LoginAAA",
    url: "someurl-aaa",
    number: 23
  },
  {
    login: "LoginDDD",
    url: "someurl-ddd",
    number: 45
  }
]

I think I have to use a filter() method but my tries don't bring the results. Should I run filter() for each array?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
NetPax
  • 111
  • 1
  • 6
  • you will have to go through first array, and cache the logins on a separate cache object : var cache = {}; and when iterating through the second array you check if they exist in the cache – Abderrahmane TAHRI JOUTI Jan 07 '18 at 18:06
  • 3
    Possible duplicate of [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Aᴍɪʀ Jan 07 '18 at 18:07
  • This is not JSON and even if you get the data as JSON, the problem has nothing to do with JSON. – Felix Kling Jan 07 '18 at 18:09
  • You may use a .map function to go trought each element of each array – Arturas Lapinskas Jan 07 '18 at 18:11
  • I think is a repeated question. See [Compare the elements of two arrays by Id and remove the elements from the one array that are not presented in the other](https://stackoverflow.com/questions/14983575/compare-the-elements-of-two-arrays-by-id-and-remove-the-elements-from-the-one-ar) – f-spin Jan 07 '18 at 18:13
  • Please post whatever code you have from your previous attempts. – ecg8 Jan 07 '18 at 18:18

1 Answers1

-1
const array1 = []; // Your first array
const array2 = []; // Your second array
const logins2 = array2.map(login => {
    return login['login'];
});
duplicates = array1.filter(login => {
    return logins2.indexOf(login['login']) !== -1;
});
Jim Wright
  • 5,905
  • 1
  • 15
  • 34