TransWikia.com

i need to remove duplicated comments from every post

Stack Overflow Asked by rabie_alkholi on February 3, 2021

data structure whats wrong with code because it’s removes old comments

mutations:{
    getPosts(state) {
              let unique = [...new Set(state.posts)];
        
              for (let i = 0; i < unique.length; i++) {
                for (let j = 0; j < unique[i].comments.length; j++) {
                  for (let k = 1; k < unique[i].comments.length; k++) {
                    if (unique[i].comments[j]._id == unique[i].comments[k]._id) {
                      unique[i].comments.splice(k, 1);
                    }
                  }
                }
              }
  return unique;
}

}

One Answer

If reassigning comments is okay, this should do the trick:

let unique = [...new Set(state.posts)];

unique.forEach((post) => {
  const seenIds = new Set();
  post.comments = post.comments.filter((c) => {
    if (seenIds.has(c._id)) {
      return false; // Already saw it
    }
    seenIds.add(c._id);
    return true;
  });
});

Answered by AKX on February 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP