I have an array of object like that :
[{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }],
And i would like group by the city, like below:
[{name: 'Peter', age: '22', hobby: 'soccer', cities: ['london', 'Paris']},
{name: 'Mario', age: '30', hobby: 'bike',cities: ['Paris', 'Madrid']},
{name: 'Rick', age: '28', hobby: 'tennis', cities: ['Berlin']}]
I try with this function by, I don't have the good array
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }],
let groups = {};
for (let i = 0; i < arrayPeople.length; i++) {
let groupName = arrayPeople[i].city;
if (!groups[groupName]) {
groups[groupName] = [];
}
groups[groupName].push(arrayPeople[i].city);
}
let arrayGroupBy= [];
for (let groupName in groups) {
arrayGroupBy.push({ ...arrayPeople, cities: groups[groupName] });
}
How I can make my group by ?
Thank for your help.
You can use Array.reduce to process your input array, using the name, age and hobby as a key to create a grouping object, and adding the city for each key to an array in that object. You can then use Object.values to grab just the values from the grouping object into an array:
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let arrayGroupBy = Object.values(arrayPeople.reduce((c, { city, ...rest }) => {
let key = Object.values(rest).join('#');
c[key] = c[key] || { ...rest, city : [] };
c[key].city.push(city);
return c;
}, {}));
console.log(arrayGroupBy);
Note the above code is dependent on the properties in the objects being in the same order in each object (in the sample data, name, age, hobby). If this might not be the case, you will need to create the key using the named properties instead, for example:
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ age: '30', hobby: 'bike', name: 'Mario', city: 'Paris' },
{ name: 'Peter', hobby: 'soccer', city: 'Paris', age: '22' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let arrayGroupBy = Object.values(arrayPeople.reduce((c, { name, age, hobby, city}) => {
let key = `${name}#${age}#${hobby}`;
c[key] = c[key] || { name, age, hobby, city : [] };
c[key].city.push(city);
return c;
}, {}));
console.log(arrayGroupBy);
Note also that all the above code is dependent on choosing a delimiter (I've used #) that will not occur in the name or hobby values. If there is no suitable delimiter character, then it is safer to use something like JSON.stringify to produce the key value e.g. for the second code block you would use:
let key = JSON.stringify([name, age, hobby]);
Your approach is pretty near to the correct solution. You are grouping persons by city. You have to turn around and group cities by person
let arrayPeople = [{ name: 'Peter', age: '22', hobby: 'soccer', city: 'london' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Paris' },
{ name: 'Peter', age: '22', hobby: 'soccer', city: 'Paris' },
{ name: 'Mario', age: '30', hobby: 'bike', city: 'Madrid' },
{ name: 'Rick', age: '28', hobby: 'tennis', city: 'Berlin' }];
let groups = {};
for (let i = 0; i < arrayPeople.length; i++) {
let groupName = arrayPeople[i].name;
if (!groups[groupName]) {
groups[groupName] = {name: arrayPeople[i].name, age: arrayPeople[i].age, hobby: arrayPeople[i].hobby, cities: []};
}
groups[groupName].cities.push(arrayPeople[i].city);
}
console.log(Object.values(groups));
This is TypeScript so I'd probably come up with the type corresponding to the final array elements: that is, remove the city property and add a cities property:
type PersonCities = Omit<typeof arrayPeople[number], "city"> & { cities: string[] };
Then you want to put all your objects into a dictionary keyed by whatever you want the grouping condition to be (converted into a string):
const peopleCities: Record<string, PersonCities> = {};
for (let p of arrayPeople) {
const { city, ...person } = p;
const groupByKey = JSON.stringify([person.name, person.hobby, person.age]);
if (!(groupByKey in peopleCities)) {
peopleCities[groupByKey] = { ...person, cities: [] };
}
peopleCities[groupByKey].cities.push(city);
}
const arrayPeopleCities = Object.values(peopleCities);
Here we're making the grouping key a JSON string of the name, hobby, and age properties in an array. And some object rest/spread syntax to copy people properties around without too much redundancy.
Playground link to code
Related
I have 2 arrays with objects.
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
],
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
],
I need to get index from users1 of that parts that are contains in users2.
As a result I should get [{1: true}, {3: true}].
I try in this way but it's not correct
const arr = user1.filter((item, index) => user2.map(i) => {
if(i.id === item.id) return {index: true}
return null;
})
You could create a Set of all ids from users2 (a Set is somewhat like an array, but allows you to quickly check if a value is in it using .has() and it only stores unique values). Once you have the set, you can use .reduce() to create a new array, where you can use .concat() if the set has the id of the object from users1:
const users1 = [{ id: 1, name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' }, { id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 3, name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const users2 = [{ id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const u2Ids = new Set(users2.map(user => user.id));
const res = users1.reduce((acc, obj, i) => u2Ids.has(obj.id) ? acc.concat({[i]: true}) : acc, []);
console.log(res);
When creating your objects you need to ensure you use computed property names when adding the index as a key {[i]: true} so that the value at i is used rather than the literal i name. The above can also be written with a for..of loop (by accessing Array.prototype.entries()), which is more efficient and (in my opinion) more readable:
const users1 = [{ id: 1, name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' }, { id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 3, name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const users2 = [{ id: 2, name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' }, { id: 4, name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }, ];
const res = [];
const u2Ids = new Set(users2.map(user => user.id));
for(const [i, obj] of users1.entries()) {
if(u2Ids.has(obj.id))
res.push({[i]: true});
}
console.log(res);
First your array don't contains ids I filtered name for now.Also filter will not work here bcs if you use filter that will just filter your array and index will no longer be the same try following instead
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }
];
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' }
];
const arr = [];
users1.forEach((item, idx) =>{
if(users2.some(u=> u.name == item.name)){
arr.push({[idx]:true})
}
});
console.log(arr)
Just another approach - with Array.reduce()
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
const arr = users1.
reduce((previousValue, currentValue, index) => {
// change here to find by id
if (users2.some(u2 => u2.name === currentValue.name) ){
// map to whatever you want
const valueToSave = {[index] : true};
return [...previousValue, valueToSave];
} else {
return previousValue;
}
}, []);
console.log(arr);
#festina, to keep it simple we map on users2, as we are trying to find objects of users1 in users2, we get index using findIndex using (id/name any unique key available) and then filter by index > 0, and format the result in required format
const users1 = [
{ name: 'John', age: 15, gender: 'M', city: 'London', country: 'UK' },
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Jinny', age: 30, gender: 'F', city: 'London', country: 'UK' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
const users2 = [
{ name: 'Jack', age: 20, gender: 'M', city: 'New York', country: 'USA' },
{ name: 'Key', age: 15, gender: 'M', city: 'Leeds', country: 'UK' },
];
// your solution
const result = users2.map((user, index) => users1.findIndex(u => u.name === user.name))
.filter(index => index > 0)
.map((i => { return { [i]: true} }));
console.log(result)
What is wrong in this if condition. I am getting the wrong result. I need to get equal values in these two objects and diff between them.
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
for (let i = 0; i < firstArr.length; i++) {
for (let j = 0; j < secondArr.length; j++) {
if (firstArr[i].name == secondArr[j].name) {
console.log('eq', firstArr[i].city, secondArr[j].city)
}
if (firstArr[i].name != secondArr[j].name) {
console.log('not found in second array', firstArr[i].city)
}
if (secondArr[j].name != firstArr[i].name) {
console.log('not found in first array', secondArr[j].city)
}
}
}
Currently you compare each element of the first array with each element of the second array. You could instead use Array.prototype.some and Array.prototype.every to filter the arrays and to find the intersection resp. difference. Then you can map the objects to the city names.
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
function intersect(lhs, rhs) {
return lhs.filter(el => rhs.some(el2 => el.name === el2.name)).map(el => el.city);
}
function diff(lhs, rhs) {
return lhs.filter(el => rhs.every(el2 => el.name !== el2.name)).map(el => el.city);
}
console.log(intersect(firstArr, secondArr));
console.log(diff(firstArr, secondArr));
console.log(diff(secondArr, firstArr));
I loop the first array first and find matches in second array. If there is a match, diff is displayed. If there is no such match, then the correct text is being displayed. An array is built along the way, which is used to simplify the loop on the second array.
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
let names = [];
for (let first of firstArr) {
let matches = secondArr.filter((second) => (first.name === second.name));
if (matches.length) {
console.log('eq', first.city, matches[0].city)
} else {
console.log('not found in second array', first.city);
}
names.push(first.name);
}
for (let second of secondArr) {
if (names.indexOf(second.name) === -1) console.log('not found in first array', second.city);
}
Try this:
const firstArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 23, city: 'Berlin' }, { name: 'Sara', age: 28, city: 'Paris' }, { name: 'Rash', age: 20, city: 'Dubai' } ];
const secondArr = [{ name: 'tom', age: 22, city: 'Madrid' }, { name: 'Alex', age: 27, city: 'Berlin' }, { name: 'Hary', age: 29, city: 'London' }, ];
var eq = [], uniqueInFirst = [], uniqueInSecond = [];
for (let i = 0; i < firstArr.length; i++) {
var secondArrCities = Object.values(secondArr).map ((obj) => {return obj.city})
if (secondArrCities.includes(firstArr[i].city)) {
eq.push(firstArr[i].city)
} else {
uniqueInFirst.push(firstArr[i].city)
}
}
for (let i = 0; i < secondArr.length; i++) {
var firstArrCities = Object.values(firstArr).map ((obj) => {return obj.city})
if (!firstArrCities.includes(secondArr[i].city)) {
uniqueInSecond.push(secondArr[i].city)
}
}
console.log(eq)
console.log(uniqueInFirst)
console.log(uniqueInSecond)
I have an array of objects with multiple fields, i.e.
Person
{
name: string;
age: number;
addressLines: string[];
}[];
I also have dynamic search parameters, i.e.
parameters: ['mary', 'oregon'] //may be a longer/shorter array
Assuming my input is:
[
{ name: 'john mark', age: '29', addressLines: ['566 long street', 'oregon']},
{ name: 'williams', age: '30', addressLines: ['oregon']},
{ name: 'moore mary', age: '40', addressLines: ['street 61', 'salt lake']}
]
My output should be:
[
{ name: 'john mark', age: '29', addressLines: ['566 long street', 'oregon']}, // oregon
{ name: 'moore mary', age: '40', addressLines: ['street 61', 'salt lake']} //mary
]
How can I implement this using the filter method? thanks in advance.
You could do it like this:
type Persons =
{
name: string;
age: number;
addressLines: string[];
}[];
const personArray: Persons = [
{ name: 'john mark', age: 29, addressLines: ['566 long street', 'oregon']},
{ name: 'williams', age: 30, addressLines: ['oregon']},
{ name: 'moore mary', age: 40, addressLines: ['street 61', 'salt lake']}
]
const parameters = ['mary', 'oregon']
const foundPersons = personArray.filter((person) => {
let matched = false
parameters.forEach((param) => {
// Check if name matches
if (person.name.includes(param)) matched = true;
// Check if address matches
person.addressLines.forEach((addressPart) => {
if (addressPart.includes(param)) matched = true;
})
// Check if age matches
if (person.age == param) matched = true;
})
return matched
})
See it in action here
PS: With your given parameters everything matches
I tried to solve the problem on my own but I did not manage to. So I decided to ask for help.
I've got an array of JSON objects like this:
const objArr = [
{
name: 'Andrew',
city: 'London'
},
{
name: 'Edouard',
city: 'Paris'
},
{
name: 'Nathalie',
city: 'London'
},
{
name: 'Patrick',
city: 'London'
},
{
name: 'Mathieu',
city: 'Paris'
}
];
I want to gather objects with same key value - in that case the city key - in a new array to obtain this:
const newObjArr = [
[{
name: 'Andrew',
city: 'London'
},
{
name: 'Nathalie',
city: 'London'
},
{
name: 'Patrick',
city: 'London'
}],
[{
name: 'Edouard',
city: 'Paris'
},
{
name: 'Mathieu',
city: 'Paris'
}]
];
This is a job for .reduce().
const objArr = [
{name: 'Andrew', city: 'London'},
{name: 'Edouard', city: 'Paris'},
{name: 'Nathalie', city: 'London'},
{name: 'Patrick', city: 'London'},
{name: 'Mathieu', city: 'Paris'}
];
// Object of arrays
const result = objArr.reduce((acc, obj) => {
return {...acc, [obj.city]: [...acc[obj.city] || [], obj]}
}, {})
// Array of arrays
const result2 = Object.values(result);
console.log(result2)
Use lodash group by and then add to new array
var objArr = [ { name: 'Andrew', city: 'London' }, { name: 'Edouard', city: 'Paris' }, { name: 'Nathalie', city: 'London' }, { name: 'Patrick', city: 'London' }, { name: 'Mathieu', city: 'Paris' } ]
var grouped = _.mapValues(_.groupBy(objArr, 'city'),
clist => clist.map(city => _.omit(city, 'city')));
var result=[]
for (const [key, value] of Object.entries(grouped)) {
var array=[]
value.forEach(x=>{
array.push({ name: x.name, city:key })
})
result.push(array);
}
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
You can use reduce to group by a field using that field as the key and then use Object.values if you really just want the values:
const objArr = [ { name: 'Andrew', city: 'London' }, { name: 'Edouard', city: 'Paris' }, { name: 'Nathalie', city: 'London' }, { name: 'Patrick', city: 'London' }, { name: 'Mathieu', city: 'Paris' } ];
var groupBy = function(array, k) {
return array.reduce(function(acc, cur) {
(acc[cur[k]] = acc[cur[k]] || []).push(cur);
return acc;
}, {});
};
console.log(Object.values(groupBy(objArr, 'city')));
I am looking to combine these two arrays into a single one. I want any id information that is the same to be filtered so that it only appears once, making it a simple list of name, age, occupation, and address.
I have tried simply concating the info, using splice, using filter... but I just cant seem to get the right answer.
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}]
I always end up with a single list after the concat, but I cant find out how to filter the same info.
Sounds like you need to merge each item of each array together - and that they're both in the same order, in which case you could do:
const newList = []
a.forEach((item, index) => {
newList.push({
...item,
...b[index]
})
})
console.log(newList)
You can make an object from first array a whole keys will be id of each object. Then use map() on b and return object having all props.
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}]
let obj = a.reduce((ac,a) => (ac[a.id] = a,ac),{});
let res = b.map(x => ({...x,...obj[x.id]}));
console.log(res)
The following will reconstruct the array in the same order as a but the function doesn't depend on b being in the same order.
var a = [{id:"aBcDeFgH",firstName:"Juan",lastName:"Doe",age:32},{id:"zYxWvUt",firstName:"Alex",lastName:"Smith",age:24}],
b = [{id:"aBcDeFgH",occupation:"architect",address:{street:"123 Main St",city:"CityTown",Country:"USA"}},{id:"zYxWvUt",occupation:"receptionist",address:{street:"555 Ocean Ave",city:"Beach City",Country:"USA"}}];
let res = a.reduce((a,c) => {a.push({...c, ...b.find(v => v.id == c.id)}); return a;},[])
console.log(res)
And as a more performant solution, that instead of using find for every look-up uses a map-like object for our second array so we just have to insert from it for our result via O(1) look-ups.
So instead of O(n²) we now have O(n):
var a = [{id:"aBcDeFgH",firstName:"Juan",lastName:"Doe",age:32},{id:"zYxWvUt",firstName:"Alex",lastName:"Smith",age:24}],
b = [{id:"aBcDeFgH",occupation:"architect",address:{street:"123 Main St",city:"CityTown",Country:"USA"}},{id:"zYxWvUt",occupation:"receptionist",address:{street:"555 Ocean Ave",city:"Beach City",Country:"USA"}}];
let tmp = b.reduce((a,c) => {a[c.id] = c; return a},{}),
res = a.reduce((a,c) => {a.push({...c, ...tmp[c.id]}); return a;},[]);
console.log(res)
If the id is the key to compare,
const concatListById = (base, target) => base.reduce((acc, c) => {
const matched = target.find(e => e.id === c.id);
let el = c;
if (matched) el = { ...matched, ...c };
acc.push(el);
return acc;
}, []);
console.log(concatListById(a, b));
If there is an assumption that id sequence of each array is the same,
const justMergeArray = (base, target) =>
base.map((e, idx) => ({ ...e, ...target[idx] }));
console.log(justMergeArray(a, b));
You can use reduce and compare if id match just push into same object and add this to an array
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}
]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}
]
const res = a.reduce((all, acc, index) => {
if (acc.id === b[index].id) {
all.push({
...acc,
...b[index]
});
}
return all;
}, []);
console.log(res);
Try this:
var a = [{
id: 'aBcDeFgH',
firstName: 'Juan',
lastName: 'Doe',
age: 32
},
{
id: 'zYxWvUt',
firstName: 'Alex',
lastName: 'Smith',
age: 24
}]
var b = [{
id: 'aBcDeFgH',
occupation: 'architect',
address: {
street: '123 Main St',
city: 'CityTown',
Country: 'USA'
}
},
{
id: 'zYxWvUt',
occupation: 'receptionist',
address: {
street: '555 Ocean Ave',
city: 'Beach City',
Country: 'USA'
}
}];
const newA = a.reduce((acc, ele) => (acc[ele.id] = ele, ele),{});
const result = b.map(ele=> ({...newA[ele.id],...ele}));
console.log(result);