0

For example, given this array of objects:

[ 
    { userid: "5", articleid: "3"},
    { userid: "5", articleid: "3"},
    { userid: "5", articleid: "3"},
    { userid: "1", articleid: "2"}
]

I want to display the values ​​this way Without repetition inside the loop:

[ 
    { userid: "5", articleid: "3"},
    { userid: "1", articleid: "2"}
]

The code used is javascript

var newMessage = '';
    function realTime(){
        db.collection('chat').where('userid', '==', <?php echo $id; ?>)
        .orderBy('time')
        .onSnapshot(function(snapshot) {
            newMessage = '';
            snapshot.docChanges().forEach(function(change) {
              if (change.type === "added") {
                //console.log(change.doc.data());
                const elements = [change.doc.data()];
                console.log([...new Set(elements.map(JSON.stringify))].map(JSON.parse));
              }
            });

            if (chatHTML != newMessage) {
                $('.msg_body').append(newMessage);
            }
        });
    }

3 Answers3

2

This is a an easy way to do it.

const elements = [ 
    { userid: "5", articleid: "3"},
    { userid: "5", articleid: "3"},
    { userid: "5", articleid: "3"},
    { userid: "1", articleid: "2"}
];
console.log([...new Set(elements.map(JSON.stringify))].map(JSON.parse));
Talmacel Marian Silviu
  • 1,321
  • 1
  • 4
  • 13
0

You can use Set with filter to achieve the desired result.

const arr = [
  { userid: "5", articleid: "3" },
  { userid: "5", articleid: "3" },
  { userid: "5", articleid: "3" },
  { userid: "1", articleid: "2" },
];

const set = new Set();

const result = arr.filter(({ userid, articleid }) => {
  if (set.has(`${userid}|${articleid}`)) return false;
  else {
    set.add(`${userid}|${articleid}`);
    return true;
  }
});

console.log(result);
decpk
  • 21,436
  • 4
  • 19
  • 37
0

You can use filter on your array to do it.

The first one allows you to filter only by userID, and the second one with both values to separate also those who are not really duplicates.

const values = [
  { userid: "5", articleid: "3" },
  { userid: "5", articleid: "3" },
  { userid: "5", articleid: "3" },
  { userid: "5", articleid: "2" },
  { userid: "1", articleid: "2" },
];

const first = values.filter(
  (element, index, array) =>
    array.findIndex(
      (otherElement) => element.userid === otherElement.userid
    ) === index
);

const second = values.filter(
  (element, index, array) =>
    array.findIndex(
      (otherElement) =>
        element.userid === otherElement.userid &&
        element.articleid === otherElement.articleid
    ) === index
);

console.log("first", first);
console.log("second", second);

By searching a little more, there was already the answer on several posts.