Por ejemplo, dada esta matriz de objetos:
[ { userid: "5", articleid: "3"}, { userid: "5", articleid: "3"}, { userid: "5", articleid: "3"}, { userid: "1", articleid: "2"} ]Quiero mostrar los valores de esta manera Sin repetición dentro del ciclo:
[ { userid: "5", articleid: "3"}, { userid: "1", articleid: "2"} ]El código utilizado es 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); } }); }Esta es una manera fácil de hacerlo.
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));Puede usar el filtro en su matriz para hacerlo.
El primero te permite filtrar solo por ID de usuario, y el segundo con ambos valores para separar también aquellos que no son realmente duplicados.
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);Buscando un poco más, ya estaba la respuesta en varias publicaciones .
Puede usar Establecer con filtro para lograr el resultado deseado.
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);