Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : Find common objects from two array using Lambda function

I am using Typescript for below problem. I want to search object not simple alphabetic or number in the list.

Below are the two arrays. I want to get common objects in separate list without using any third party library.

    firstArray = [
           {
               "id": 4,
               "name": "Tata"
           },
           {
               "id": 11,
               "name": "Maruti"
           },
           {
               "id": 14,
               "name": "Mahindra"
           }
        ]

        secondArray = [
           {
               "id": 4,
               "name": "Tata"
           },
           {
               "id": 11,
               "name": "Maruti"
           },
           {
               "id": 15,
               "name": "Hyundai"
           },
           {
               "id": 21,
               "name": "Honda"
           } 
        ]
        
// Get Common Elements
// I am getting blank array as output

        console.log(firstArray.filter(( make ) => secondArray.includes( make)));

Is there good function or way to find out commons element?

like image 375
Morez Avatar asked May 02 '18 12:05

Morez


People also ask

How do you get common elements from two arrays in TypeScript?

You can use array#filter with array#some . For each object in the first array, check if id and name exist in the other array. Save this answer.

How do I group an array of objects in Javascript?

The most efficient method to group by a key on an array of objects in js is to use the reduce function. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.


2 Answers

You can use array#filter with array#some. For each object in the first array, check if id and name exist in the other array.

const firstArray = [{ "id": 4, "name": "Tata" }, { "id": 11, "name": "Maruti" }, { "id": 14, "name": "Mahindra" } ], 
      secondArray = [{ "id": 4, "name": "Tata" }, { "id": 11, "name": "Maruti" }, { "id": 15, "name": "Hyundai" }, { "id": 21, "name": "Honda" } ],
      result = firstArray.filter(o => secondArray.some(({id,name}) => o.id === id && o.name === name));
console.log(result);
like image 53
Hassan Imam Avatar answered Nov 12 '22 03:11

Hassan Imam


For ES6, you can also try sets,

For demonstration,

const thirdArray = [...new Set([...firstArray ,...secondArray])];
like image 30
Mohib Wasay Avatar answered Nov 12 '22 03:11

Mohib Wasay