I have below array
const array = [
{
key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
location: { lat: '22.7196', lng: '75.8577' },
address: { city: 'NY', country: 'USA' },
className: 'FourthActivity',
deviceId: '1111111111111111'
},
{
key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
location: { lat: '22.7196', lng: '75.8577' },
address: { city: 'NY', country: 'USA' },
className: 'FourthActivity',
deviceId: '222222222222222'
},
{
key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ',
location: { lat: '22.7196', lng: '75.8577' },
address: { city: 'Landon', country: 'UK' },
className: 'FourthActivity',
deviceId: '33333333333'
}
]
I have to group it by using two properties inside the object ie address
and className
. How can I do this either with loadash or javascript?
expected output
[{
address: { city: 'NY', country: 'USA' }, className: 'FourthActivity',
count: 2,
data: [{
deviceId: 222222222222222,
}, {
deviceId: 1111111111111111,
}]
}, {
address: { city: 'Landon', country: 'UK' }, className: 'FourthActivity',
count: 1,
data: [{
deviceId: 33333333333,
}]
}]
I have tried this but doesn't work
var selectedVehicle = _.filter(array, 'address')
const selectedVehicles = _.groupBy(selectedVehicle, function(item) {
return item.makeCode;
})
console.log(selectedVehicles)
You can reduce
into an object, creating { address, className, count: 0, data: [] }
if it doesn't exist for the given address / className pair yet, and then get that object's values:
const array = [ { key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ', location: { lat: '22.7196', lng: '75.8577' }, address: { city: 'NY', country: 'USA' }, className: 'FourthActivity', deviceId: '1111111111111111' }, { key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ', location: { lat: '22.7196', lng: '75.8577' }, address: { city: 'NY', country: 'USA' }, className: 'FourthActivity', deviceId: '222222222222222' }, { key: 'TSJUcgLGig2UOdjAzlqq4KW5GK6PKXHC2ndw40HYIss7EKsV6nJ', location: { lat: '22.7196', lng: '75.8577' }, address: { city: 'Landon', country: 'UK' }, className: 'FourthActivity', deviceId: '33333333333' } ] const output = Object.values(array.reduce((a, { address, className, deviceId }) => { const addressClassNameStr = JSON.stringify({ address, className }); if (!a[addressClassNameStr]) { a[addressClassNameStr] = { address, className, count: 0, data: [] }; } a[addressClassNameStr].count++; a[addressClassNameStr].data.push({ deviceId }); return a; }, {})); console.log(output);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.