const objArr = [
{
name: "Andrew",
city: "London",
},
{
name: "Edouard",
city: "Paris",
},
{
name: "Nathalie",
city: "London",
},
{
name: "Patrick",
city: "London",
},
{
name: "Mathieu",
city: "Paris",
},
];
// Gather all the different cities
let allCities = [];
objArr.forEach( _x => {
let city = _x.city;
if (! allCities.includes(city)) {
allCities.push(city);
};
});
// Format 1
/*
{
London: [
{ name: 'Andrew', city: 'London' },
{ name: 'Nathalie', city: 'London' },
{ name: 'Patrick', city: 'London' }
],
Paris: [
{ name: 'Edouard', city: 'Paris' },
{ name: 'Mathieu', city: 'Paris' }
]
}
*/
let newObjArr1 = {};
allCities.forEach( _city => {
newObjArr1[_city] = objArr.filter( _x => {
return _x.city === _city
});
});
console.log( newObjArr1 );
// Format 2
/*
[
[
{ name: 'Andrew', city: 'London' },
{ name: 'Nathalie', city: 'London' },
{ name: 'Patrick', city: 'London' }
],
[
{ name: 'Edouard', city: 'Paris' },
{ name: 'Mathieu', city: 'Paris' }
]
]
*/
let newObjArr2 = [];
for (let _i = 0; _i < allCities.length; _i ++) {
let _city = allCities[_i];
newObjArr2[_i] = objArr.filter( _x => {
return _x.city === _city
});
};
console.log( newObjArr2 );