Concating two arrays into one - javascript

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);

Related

JS - compare 2 arrays by key, return 4 arrays: matches & unmatches from each

Interface -
interface I {
name: string;
age: number;
city: string;
address?: string;
}
Arrays -
const arr1: I[] = [
{
name: "daniel",
age: 21,
city: 'NYC'
},
{
name: "kosta",
age: 28,
city: "NYC"
},
{
name: "yoav",
age: 28,
city: "NYC"
}
];
const arr2: I[] = [{
name: "daniel",
age: 21,
city: "NYC",
address: 'E. 43'
},
{
name: "simon",
age: 24,
city: "NYC",
address: 'E. 43'
},
{
name: "david",
age: 22,
city: "NYC",
address: 'E. 43'
},
{
name: "kosta",
age: 28,
city: "NYC",
address: 'E. 43'
}
];
Getting keys for the arrays -
const arr1Map: ReadonlyMap<string, string | undefined> = new Map(
arr1.map(
({
name, age, city, address
}) => [
`${name}|${age}|${city}`,
address
]
)
);
const arr2Map: ReadonlyMap<string, string | undefined> = new Map(
arr2.map(
({
name, age, city, address
}) => [
`${name}|${age}|${city}`,
address
]
)
);
Empty arrays -
let arr1Match: I[] = []
let arr1Unmatch: I[] = []
let arr2Match: I[] = []
let arr2Unmatch: I[] = []
What I need to do now is to campare all values in arr1 to arr2, if there is a match, store the match from arr1 in arr1Match and the match from arr2 in arr2Match. If there is an Unmatch I need to store the unmatch arr1 in arr1Unmatch and the unmatch from arr2 in arr2Unmatch.
And if there is a match I need to store the address from arr2 into arr1.
The desierd output -
arr1Match: [{ name: "daniel", age: 21, city: "NYC", address: 'E. 43' }, { name: "kosta", age: 28, city: "NYC", address: 'E. 43' } ]
arr2Match: [{ name: "daniel", age: 21, city: "NYC", address: 'E. 43' }, { name: "kosta", age: 28, city: "NYC", address: 'E. 43' }]
arr1Unmatch: [{ name: "yoav", age: 28, city: "NYC" }]
arr2Unmatch: [{ name: "simon", age: 24, city: "NYC", address: 'E. 43' }, { name: "david", age: 22, city: "NYC", address: 'E. 43' }]
The answer depends on some questions about your needs: What constitutes a match? If there's different data between the matches, what should be put in the match array? Should the arrays point to the original objects, or to copies of them?
Also, it looks like there is no difference between arr1Match and arr2Match, so those can be combined into one
Either way the solution would be to iterate over one array, and search for a match in the other array for every value. Any item that doesn't match will go to the unmatch arrays
// Replace with real match logic
const isMatch = <T>(a: T, b: T) => Math.random() < 0.5;
const getMatches = <T>(arrOne: T[], arrTwo: T[]) => {
const matches: T[] = [];
const arrOneUnmatches: T[] = [];
let arrTwoUnmatches: T[];
// Copying for comfortability's sake
const arrTwoCopy = [...arrTwo];
arrOne.forEach(item => {
// Find a match in array two
const arrTwoMatchIndex = arrTwoCopy.findIndex(arrTwoItem => isMatch(item, arrTwoItem));
if (arrTwoMatchIndex) {
matches.push(item);
// Remove it from arrTwoCopy, to maintain arrTwoUnmatches
arrTwoCopy.splice(arrTwoMatchIndex, 1);
} else {
// No match = go to arrOneUnmatches
arrOneUnmatches.push(item);
}
})
// Anyone left in arrTwoCopy didn't match anyone in arrOne, so they have no match
arrTwoUnmatches = arrTwoCopy;
return { matches, arrOneUnmatches, arrTwoUnmatches }
}

Get most Senior

friends!
I need your help.
A list of information about people is given.
An array containing the oldest person in the list must be returned. If several people are of the same highest age, then an array should be returned containing all of them.
The age is stored in the "age" field.
Input data:
const data =[
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
]
const result = getMostSenior(data);
Output data:
console.log(result);
// [
// { firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
// { firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
// ]
My try:
const getMostSenior = humans => {
let oldestHuman = humans.reduce((oldest, human) => {
return oldest.age > human.age ? oldest : human;
})
return oldestHuman
};
But this only returns an array containing the oldest person in the list.
Can't figure out how to return an array where multiple people have the same maximum age.
Please, help.
This is not an efficient implementation though!
function getMostSenior(data){
const ageArray = [];
const agedPersons = {};
data.forEach((item)=>{
const age = item.age;
ageArray.push(age);
if(agedPersons.hasOwnProperty(age)){
agedPersons[age].push(item);
}
else{
agedPersons[age] = [];
agedPersons[age].push(item);
}
});
ageArray.sort();
return [...agedPersons[ageArray[ageArray.length-1]]];
}
Instead of pushing the object to the accumulator you should return only the age. You can then use filter on the data to get all those objects where the age matches the value of that variable.
const data=[{firstName:"Gabriel",lastName:"X.",country:"Monaco",continent:"Europe",age:49,language:"PHP"},{firstName:"Odval",lastName:"F.",country:"Mongolia",continent:"Asia",age:38,language:"Python"},{firstName:"Emilija",lastName:"S.",country:"Lithuania",continent:"Europe",age:19,language:"Python"},{firstName:"Sou",lastName:"B.",country:"Japan",continent:"Asia",age:49,language:"PHP"}];
function getMostSenior(data) {
const oldest = data.reduce((oldest, c) => {
return c.age > oldest ? c.age : oldest;
}, 0);
return data.filter(obj => obj.age === oldest);
}
console.log(getMostSenior(data));
The alternative to using reduce for this task would be to use a for...of loop to iterate over the array and update a variable if the age value of an object is greater than the current value of the variable.
const data=[{firstName:"Gabriel",lastName:"X.",country:"Monaco",continent:"Europe",age:49,language:"PHP"},{firstName:"Odval",lastName:"F.",country:"Mongolia",continent:"Asia",age:38,language:"Python"},{firstName:"Emilija",lastName:"S.",country:"Lithuania",continent:"Europe",age:19,language:"Python"},{firstName:"Sou",lastName:"B.",country:"Japan",continent:"Asia",age:49,language:"PHP"}];
function getMostSenior(data) {
let oldest = 0;
for (const { age } of data) {
if (age > oldest) oldest = age;
}
return data.filter(obj => obj.age === oldest);
}
console.log(getMostSenior(data));
I think this is little optimal way to solve your problem using Array Reduce
var data =[
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
var output = data.reduce((a, c) => {
if (a.length) {
if (a[0].age < c.age)
a = [c];
else if (a[0].age == c.age)
a.push(c)
} else {
a = [c];
}
return a;
}, []);
console.log(output);

Why is my condition that checks diff between two arrays of objects wrong?

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)

Group by array object by object

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

Gathering JSON objects with same key value

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')));

Categories

Resources