简体   繁体   中英

Sort objects based on property value

I have Array of Objects, how can I go about searching all objects and categorise them based on property value

 data = [ 
  {key: 1, val: Mon, week: 0},
  {key: 1, val: Wed, week: 0},
  {key: 1, val: Mon, week: 1},
  {key: 1, val: Mon, week: 1}
  {key: 1, val: Mon, week: 2}
]

Desired output

week0Array = [{key: 1, val: Mon, week: 0},{key: 1, val: Wed, week: 0}]
week1Array = [{key: 1, val: Mon, week: 1}, {key: 1, val: Mon, week: 1} ]
week2Array = [{key: 1, val: Mon, week: 2}]

I have tried to use find in lodash kept getting undefined

_.find(collection, [predicate=_.identity], [fromIndex=0])

You can use _.groupBy(collection, [iteratee=_.identity]) like this:

 let data = [ {key: 1, val: 'Mon', week: 0}, {key: 1, val: 'Wed', week: 0}, {key: 1, val: 'Mon', week: 1}, {key: 1, val: 'Mon', week: 1}, {key: 1, val: 'Mon', week: 2} ] let weekGroups = _.groupBy(data, d => d.week) console.log(weekGroups[0]) console.log(weekGroups[1]) console.log(weekGroups[2]) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

Please note that weekGroups is an Object and not an Array .

Just as a POJS alternative and assuming that the data is sorted to start with, reduce can create an array with the objects grouped into subarrays based on week. If sorting is required, it can be tacked on before the call to reduce:

 var data = [ {key: 1, val: "Mon", week: 0}, {key: 1, val: "Wed", week: 0}, {key: 1, val: "Mon", week: 1}, {key: 1, val: "Mon", week: 1}, {key: 1, val: "Mon", week: 2} ]; var result = data.reduce((acc, obj, i) => { i && acc[acc.length-1].week == obj.week ? acc[acc.length-1].push(obj) : acc.push([obj]); return acc; }, []); console.log(result) 

The brackets in the conditional ? : ? : aren't required but I think they aid readability.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM