Home > Net >  How to get same values from 2 arrays with objects in ES6 Javascript?
How to get same values from 2 arrays with objects in ES6 Javascript?

Time:09-17

So I have here two different arrays.

const test = [
    { firstName: "John", lastName: "Doe" },
    { firstName: "Michael", lastName: "Sins" },
    { firstName: "Alex", lastName: "Brown" }
  ];
const test2 = [
    { firstName: "Lisa", lastName: "Shore" },
    { firstName: "John", lastName: "Doe" },
    { firstName: "Justin", lastName: "Park" },
  ];

What I want is to get the same values from the two arrays using ES6 (filter if possible) or in any way that fits to achieve the output. The result that I want to get is :

[{ firstName: "John", lastName: "Doe" }]

CodePudding user response:

You can try using Array.prototype.filter() and Array.prototype.some()

const test = [
    { firstName: "John", lastName: "Doe" },
    { firstName: "Michael", lastName: "Sins" },
    { firstName: "Alex", lastName: "Brown" }
  ];

const test2 = [
    { firstName: "Lisa", lastName: "Shore" },
    { firstName: "John", lastName: "Doe" },
    { firstName: "Justin", lastName: "Park" },
  ];

const res = test.filter(t1 => test2.some(t2 => 
                    t1.firstName == t2.firstName 
                    && t1.lastName == t2.lastName
                  ));
console.log(res);

CodePudding user response:

Thi swill still works if you have object with properties other than firstName and lastName

const test = [
    { firstName: "John", lastName: "Doe" },
    { firstName: "Michael", lastName: "Sins" },
    { firstName: "Alex", lastName: "Brown" }
  ];
  
  const test2 = [
    { firstName: "Lisa", lastName: "Shore" },
    { firstName: "John", lastName: "Doe" },
    { firstName: "Justin", lastName: "Park" },
  ];
  
  const tempTest2 = test2.map(item => JSON.stringify(item));
  
  const result = test.filter(item => tempTest2.includes(JSON.stringify(item)));
  
  console.log(result);

CodePudding user response:

You can do:

const test = [{ firstName: 'John', lastName: 'Doe' },{ firstName: 'Michael', lastName: 'Sins' },{ firstName: 'Alex',lastName: 'Brown' }]
const test2 = [{ firstName: 'Lisa', lastName: 'Shore' },{ firstName: 'John', lastName: 'Doe' },{ firstName: 'Justin',lastName: 'Park' }]


const getFullName = ({ firstName, lastName }) => firstName   lastName
const test2Names = test2.map(getFullName)
const result = test.filter((o) => test2Names.includes(getFullName(o)))

console.log(result)

  • Related