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?
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.
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.
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);
For ES6, you can also try sets,
For demonstration,
const thirdArray = [...new Set([...firstArray ,...secondArray])];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With