0

I want to combine data with the same date in the array. I'm not good enough, so I can't think of a code to make it come out like a result I'd appreciate it if you could help me

const list1 = [{
  date: "2022-10-01",
  images: [{image: "01"}, {image: "02"}, {image: "03"}]
        }]
const list2 = [{
    date: "2022-10-01",
    images: [{ image: "04"}]
     },
     {date: "2022-10-02",
      images: [{image: "05"}, {image: "06"}, { image: "07"}]
     }
   ]


result = [{
    date: "2022-10-01",
    images: [{image: "01"}, {image: "02"}, {image: "03"}, {image: "04"}]
  },
  {
    date: "2022-10-02",
    images: [{image: "05"}, {image: "06"}, {image: "07"}]
  }
]
corete
  • 1
  • 1
  • 1
    So as i understood you want to concat objects with same date? I can not see where you have removed duplicates – Sandex Oct 02 '22 at 17:15
  • Does this answer your question? [javascript | Object grouping](https://stackoverflow.com/questions/21776389/javascript-object-grouping) – ATP Oct 02 '22 at 17:21

1 Answers1

0

You could start concatenating list1 and list2.

Then you could iterate the whole array, and for each item check whether you already stored in result an object with the same date value.

If that's the case, you concat the images array for that item, otherwise you push the item in result.

const list1 = [{
  date: "2022-10-01",
  images: [{
    image: "01"
  }, {
    image: "02"
  }, {
    image: "03"
  }]
}]
const list2 = [{
    date: "2022-10-01",
    images: [{
      image: "04"
    }]
  },
  {
    date: "2022-10-02",
    images: [{
      image: "05"
    }, {
      image: "06"
    }, {
      image: "07"
    }]
  }
]


const expectedResult = [{
    date: "2022-10-01",
    images: [{
      image: "01"
    }, {
      image: "02"
    }, {
      image: "03"
    }, {
      image: "04"
    }]
  },
  {
    date: "2022-10-02",
    images: [{
      image: "05"
    }, {
      image: "06"
    }, {
      image: "07"
    }]
  }
]


const both = list1.concat(list2)
const result = []

for (const obj of both) {
  const index = result.findIndex(r => r.date === obj.date)

  if (index >= 0) {
    result[index].images = result[index].images.concat(obj.images)
  } else {
    result.push(obj)
  }
}

console.log(result)

console.log(JSON.stringify(result) === JSON.stringify(expectedResult))
GrafiCode
  • 3,307
  • 3
  • 26
  • 31