Shahariar Rahman Sajib
Shahariar Rahman Sajib

Reputation: 157

How to merge duplicate array?

const data = 
    [{notification_id: 124, user_id: 10, story_id: 25, string: "liked on your story" }
     {notification_id: 125, user_id: 12, story_id: 25, string: "liked on your story" }
     {notification_id: 126, user_id: 15, story_id: 25, string: "liked on your story" }]

output: user 10,12 and 15 liked on your story ID 25

I want to show output like above. How to merge and show those like the output. Any idea?

Upvotes: 0

Views: 55

Answers (2)

Minh Viet
Minh Viet

Reputation: 61

I cann't comment. So i write here!

Are you wanting ...

result = [
    {
        story_id : 25,
        user_id : [10, 12, 15]
    }
]

Right?

This is solution of me

const data = 
    [{notification_id: 124, user_id: 10, story_id: 25, string: "liked on your story" }
     {notification_id: 125, user_id: 12, story_id: 25, string: "liked on your story" }
     {notification_id: 126, user_id: 15, story_id: 25, string: "liked on your story" }]

var result = data.reduce((res, item) => {
    let storyID = item.story_id;
    if (typeof res[storyID] == 'undefined') {
        res[storyID] = {
            story_id: storyID,
            user_id: []
        }
    }
    res[storyID].user_id.push(item.user_id);
    return res;
}, []);

result = Object.values(result);

Upvotes: 0

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8168

You need to create a hash map, check the code snippet below:

const allData = [
  { name: 'John', story: 1 },
  { name: 'Ross', story: 2 },
  { name: 'Taylor', story: 1 },
  { name: 'Jimmy', story: 2 },
  { name: 'Amanda', story: 3 },
];

const hash = {};
for (let data of allData) {
  if (data.story in hash) hash[data.story] = [...hash[data.story], { ...data }];
  else hash[data.story] = [{ ...data }];
}
console.log(hash);

You should use Map, which is what I would suggest. The code below does the same thing but using Maps.

const allData = [
  { name: 'John', story: 1 },
  { name: 'Ross', story: 2 },
  { name: 'Taylor', story: 1 },
  { name: 'Jimmy', story: 2 },
  { name: 'Amanda', story: 3 },
];

const hash = new Map();

for(let data of allData) {
  const currentVal = hash.get(data.story);

  if (currentVal) hash.set(data.story, [...currentVal, {...data}])
  else hash.set(data.story, [{...data}])
}
console.log(hash);

Upvotes: 1

Related Questions