I am using javascript Stomp client to subscribe when server sent the message.
I need to create a new array of subscribed messages. Each message has different id. If the id exists then nothing will be pushed, but if the array does not exist then new object will be pushed to the empty array.
This is What I have tried
CODE:
var recivedData = []
connect()
function connect() {
var socket = new SockJS('/info-app');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/info', function (msg) {
var parsedData = JSON.parse(msg.body)
if(!(recivedData.length)){
recivedData.push(parsedData)
console.log(recivedData)
}
if(recivedData.length){
if(recivedData.find(e => e.id === parsedData.id)){
console.log(" there")
console.log(recivedData)
}
if(recivedData.find(e => e.id !== parsedData.id)){
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});
});
}
whenever new id enters it is pushing to the array, but if the same id enters again it is also pushing.
How can I solve that? thanks in advance
You don't want to execute if(recivedData.length){
block after you already pushed data into first empty array. Use else
part of the if
statement:
stompClient.subscribe('/topic/info', function(msg) {
var parsedData = JSON.parse(msg.body)
if (!recivedData.length) {
recivedData.push(parsedData)
console.log(recivedData)
} else {
if (recivedData.some(e => e.id === parsedData.id)) {
console.log(" there")
console.log(recivedData)
} else {
console.log("not there")
recivedData.push(parsedData)
console.log(recivedData)
}
}
console.log(recivedData)
});