Home > front end >  Filter an array of object to remove the duplicates and get some properties for that duplicate object
Filter an array of object to remove the duplicates and get some properties for that duplicate object

Time:09-30

pls help me out to solve this below problem.

the below one is the main array

let arr1 = [
   {grId: 2, grTitle: "cls 1", secTitle: "sec A"},
   {grId: 2, grTitle: "cls 1", secTitle: "sec B"},
   {grId: 3, grTitle: "cls 2", secTitle: "sec A"},
   {grId: 3, grTitle: "cls 2", secTitle: "sec B"},
 ]

I want filter like below array of object

let newArr = [
   {id: 2, title: "cls 1", secList: [{secTitle: "sec A"}, {secTitle: "sec B"}]}
   {id: 3, title: "cls 2", secList: [{secTitle: "sec A"}, {secTitle: "sec B"}]}
 ]

CodePudding user response:

Using Lodash:

let arr1 = [
  {grId: 2, grTitle: "cls 1", secTitle: "sec A"},
  {grId: 2, grTitle: "cls 1", secTitle: "sec B"},
  {grId: 3, grTitle: "cls 2", secTitle: "sec A"},
  {grId: 3, grTitle: "cls 2", secTitle: "sec B"},
]

console.log(
  _.values(
    _.map(
      _.groupBy(arr1, "grId"),
      (values) => ({
        id: values[0].grId,
        title: values[0].grTitle,
        secList: _.map(values, ({ secTitle }) => ({ secTitle })),
      })
    )
  )
)
<script src="https://unpkg.com/lodash"></script>

CodePudding user response:

the previous post was suggesting to use reduce in my opinion reduce is much harder to read so I chose to use loops instead, but feel free to change it to your liking.

let arr1 = [
   {grId: 2, grTitle: "cls 1", secTitle: "sec A"},
   {grId: 2, grTitle: "cls 1", secTitle: "sec B"},
   {grId: 3, grTitle: "cls 2", secTitle: "sec A"},
   {grId: 3, grTitle: "cls 2", secTitle: "sec B"},
 ]

let lookupTable = {};

for (const item of arr1) {
  if (item.grId in lookupTable) {
    lookupTable[item.grId].secList.push({secTitle: item.secTitle });
  } else {
    lookupTable[item.grId] = {title: item.grTitle, secList: [{ secTitle: item.secTitle }] };
  }
}

let newArr = [];
for (const [id, item] of Object.entries(lookupTable)) {
  newArr.push({id, title: item.title, secList: item.secList });
}

console.log(newArr);

/*
let newArr = [
   {id: 2, title: "cls 1", secList: [{secTitle: "sec A"}, {secTitle: "sec B"}]}
   {id: 3, title: "cls 2", secList: [{secTitle: "sec A"}, {secTitle: "sec B"}]}
 ]*/
  • Related