0

I want to make this

const arr = [
    {
        "name": "mac"
    },
    {
        "group": "others",
        "name": "lenovo"
    },
    {
        "group": "others",
        "name": "samsung"
    }
]

into this:



 [
   {
     name: 'mac',
   },
   {
     name: 'others',
     group: [
       {
         name: 'lenovo',
       },
       {
         name: 'samsung',
       },
     ],
   }
 ]

I tried to use normal forEach loop but it didn't turn out well:

let final = []
const result = arr.forEach(o => {
    if(o.group) {
        group = []
        group.push({
            name: o.name
        })
        final.push(group)
    } else {
        final.push(o)
    }
});

Not sure if reduce might help? before I try lodash groupBy I want to use just pure js to try to make it.

Jenny Le
  • 33
  • 4

2 Answers2

0

instead of creating and pushing group array in final again and again u should just push group in the end of foreach like this--

let final = []
let group = []
const result = arr.forEach(o => {
    if(o.group) {
        
        group.push({
            name: o.name
        })
    } else {
        final.push(o)
    }
})
final.push({name: "others", group})
Dev Garg
  • 1
  • 3
0

Hope this answer will work for you.

const arr = [
  {
    name: "mac",
  },
  {
    group: "others",
    name: "lenovo",
  },
  {
    group: "others",
    name: "samsung",
  },
];

const temp = [];
arr.forEach((e) => {
  if (!e.group) {
    temp.push(e);
  } else {
    const index = temp.findIndex((ele) => ele.name === e.group);
    if (index === -1) {
      obj = {
        name: e.group,
        group: [{ name: e.name }],
      };
      temp.push(obj)
    } else {
      temp[index].group.push({ name: e.name });
    }
  }
});

console.log(temp);
Mr.Developer
  • 489
  • 2
  • 8