Search code examples
javascriptarraysgroupingreducekey-value

From an array of data items how to group, create and collect other, key specific data?


I have an array of objects that looks like below

var FinalArray = [
{"jArray":[{"Cd":"A"}],"Ref":{"docId":"123"},"name":"bene","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
{"jArray":[{"Cd":"A"}],"Ref":{"docId":"456"},"name":"leg","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
{"jArray":[{"Cd":"B"}],"Ref":{"docId":"123"},"name":"bene","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
{"jArray":[{"Cd":"B"}],"Ref":{"docId":"456"},"name":"leg","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
{"jArray":[{"Cd":"A"}],"Ref":{"docId":"789"},"name":"hello","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"}];

I am trying to loop through the array and return an array of items group by the key "name" which will hold indexes of the items with same key.

expected result like below:

[
{bene: [0,2]},
{leg: [1,3]},
{hello: [4]}
]

I've put together the below but can't get it to work.

var obj = FinalArray.reduce(function(agg, item, index, f) {
  var name = item.name || ""
  var index = FinalArray.findIndex(item)
/*   var copy = [...item.jArray];
   */  if (!agg[name]) {
 
    agg[name] = []
  }
  agg[name].push(index)

  return agg;
}, {})

fairly new to using reduce and groupby. any help is appreciated. Thanks


Solution

  • You can generate an object of the names with their indexes with a reduce on the original array, just pushing indexes into the array for each name.

    If you then want an array of those values (I'm not sure this is a better structure), you can use Object.entries to get the key value pairs and map those into individual objects in an array

    var FinalArray = [
    {"jArray":[{"Cd":"A"}],"Ref":{"docId":"123"},"name":"bene","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
    {"jArray":[{"Cd":"A"}],"Ref":{"docId":"456"},"name":"leg","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
    {"jArray":[{"Cd":"B"}],"Ref":{"docId":"123"},"name":"bene","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
    {"jArray":[{"Cd":"B"}],"Ref":{"docId":"456"},"name":"leg","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"},
    {"jArray":[{"Cd":"A"}],"Ref":{"docId":"789"},"name":"hello","check1":false,"check2":false,"check3":false,"check4":false,"id":"0001"}];
    
    var obj = FinalArray.reduce((acc, { name }, i) => {
      acc[name] = (acc[name] || []).concat([i])
      return acc
    }, {})
    
    console.log(obj)
    
    objArray = Object.entries(obj).map(([k, v]) => ({ [k] : v }))
    console.log(objArray)
    .as-console-wrapper { max-height: 100% !important; top: 0; }