Sean
Sean

Reputation: 534

Create associative array from function in Javascript

I have a function (below) that filters an array for a particular channel that is passed into the function as a parameter and then returns the number of different ConversationIDs against that channel:

var conversationsByChannel = function (channel) {
    var conversations = transcriptsData.jsonarray
    .filter(ConversationID => ConversationID.MessageChannel===channel)
    .map(({ConversationID}) => ConversationID);

    var distinctConversations = [...new Set(conversations)];

    return {[channel]: distinctConversations.length}
};

An example of transcriptsData below:

var transcriptsData = {
    "jsonarray": [
        {"Type":"trace","MessageID":"aHEeHB0t0hHr7175E07zF8kfVjGLBRMdzD_oYUEHNE71Va3wN0yJv9aBAzkOk6JMZvTBRMzBNCUjCvTRuxrAVA","MessageTime":"2019-08-07T09:19:45.342Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Symptoms","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"What are the symptoms of schizophrenia?\"]","Answer":"🙊\nThe symptoms of schizophrenia are usually classified into:\n\n* Positive symptoms – any change in behaviour or thoughts, such as hallucinations or delusions\n* Negative symptoms – a withdrawal or lack of function that you would not usually expect to see in a healthy person; for example, people with schizophrenia often appear emotionless and flat","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":150,\"qna\":null,\"displayText\":\"Related Issues\"}]"}
        ,{"Type":"trace","MessageID":"hLgPSyBP-cAPdKYJ-bFHUckfVjGLBRMdzD_oYUEHNE4bJsq-K4GZvHL9m6guIMtShXFRY-XoxTMdZVBLLZBGDQ","MessageTime":"2019-08-07T09:19:39.582Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Schizophrenia","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"What is schizophrenia?\"]","Answer":"🤔\nViews on schizophrenia have changed over the years. Lots of people question whether it's really a distinct condition, or actually a few different conditions that overlap. But you may still be given this diagnosis if you experience symptoms such as:\n\n* psychosis (such as hallucinations or delusions)\n\n* disorganised thinking and speech\n\n* feeling disconnected from your feelings\n\n* difficulty concentrating\n\n* wanting to avoid people\n\n* a lack of interest in things\n\n* not wanting to look after yourself.\n\nBecause psychiatric experts disagree about what schizophrenia is, some people argue that this term shouldn't be used at all. Others think the name of the condition doesn't matter, and prefer to just focus on helping you manage your symptoms and meeting your individual needs.","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":147,\"qna\":null,\"displayText\":\"Prevalence\"},{\"displayOrder\":0,\"qnaId\":148,\"qna\":null,\"displayText\":\"Causes\"},{\"displayOrder\":0,\"qnaId\":149,\"qna\":null,\"displayText\":\"Symptoms\"},{\"displayOrder\":0,\"qnaId\":150,\"qna\":null,\"displayText\":\"Related Issues\"}]"}
        ,{"Type":"trace","MessageID":"893qgqa3cR9","MessageTime":"2019-08-07T09:19:27.853Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"WHAT_IS_MENTAL_HEALTH","MessageRecipientID":"530667464425015","QuickReplyDisplayText":"Mental Health","QuickReplyPayload":"WHAT_IS_MENTAL_HEALTH","Question":"[\"What is mental health?\"]","Answer":"🤔\nIn many ways, Mental Health is just like Physical Health: Everybody has it and we need to take care of it.\n\nGood Mental Health means being generally able to think, feel and react in the ways that you need and want to live your life. But if you go through a period of poor Mental Health you might find the ways you're frequently thinking, feeling or reacting become difficult, or even impossible, to cope with. This can feel just as bad as a physical illness, or even worse.\n\nMental Health problems affect around one in four people in any given year. They range from common problems, such as depression and anxiety, to rarer problems such as schizophrenia and bipolar disorder.","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":123,\"qna\":null,\"displayText\":\"What Types Are There?\"}]"}
        ,{"Type":"trace","MessageID":"V2VFDEjUb_w3uoJwMwdHYckfVjGLBRMdzD_oYUEHNE7ufPEJdVsZzedQSKsLniMtd9-f_Ngy-mk-tNd1w3X33w","MessageTime":"2019-08-07T09:19:57.637Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Suicide","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"How common is suicide?\"]","Answer":"🤓\nApproximately 6.7% of people have attempted suicide during their lifetime in the UK","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":195,\"qna\":null,\"displayText\":\"Get Help\"}]"}
        ,{"Type":"trace","MessageID":"V2VFDEjUb_w3uoJwMwdHYckfVjGLBRMdzD_oYUEHNE7ufPEJdVsZzedQSKsLniMtd9-f_Ngy-mk-tNd1w3X33w","MessageTime":"2019-08-07T09:19:57.637Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Suicide","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"How common is suicide?\"]","Answer":"🤓\nApproximately 6.7% of people have attempted suicide during their lifetime in the UK","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":195,\"qna\":null,\"displayText\":\"Get Help\"}]"}
        ,{"Type":"trace","MessageID":"RLOUlqwIcO4zSY4zHgWG78kfVjGLBRMdzD_oYUEHNE7gRJSePak9st7_nIIgw3OWXLvAMm4hMXeJ5kFnlIavpQ","MessageTime":"2019-08-07T09:20:04.294Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Get Help","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"Help me\"]","Answer":"🆘\nBeing in a crisis can be very frightening. If you are worried about your safety, thinking of self-harm or feeling suicidal please get some help and support ASAP.\n\nWhen you're in a criss due to Mental Health problems or struggling to deal with your NeuroDiversity it can be difficult to know what to do. Everyone is deserving of support and it's vitally important that you get some when in crisis.\n\nPlease follow this link for details of where you can get help:\n\nhttps://www.mihnd.co.uk/crisis","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":196,\"qna\":null,\"displayText\":\"Help Yourself\"}]"}
    ]
};

This works well at creating an associative array for an individual channel and will return the following (using Facebook as an example channel):

{facebook:1}

What I want to do is to use this function to create an associative array of all the channels and the number of ConversationIDs as key:value pairs. For example:

{facebook:1, webchat:1, slack:1}

I've been trying various techniques to run the function and combine the returned arrays but can't get any further than an associative array that sets the keys as the index value as per the below:

0:{facebook:1}, 1:{webchat:1}, 2:{slack:1}

I believe this is because I'm using curly brackets to return my array from the function but can't find a way for the function to work without them.

Upvotes: 1

Views: 101

Answers (2)

Cat
Cat

Reputation: 4246

Here's a classic way to count occurrences of values in an array:

var transcriptsData = {
  "jsonarray": [
    { "MessageChannel" : "channel1", "ConversationID" : "11111" },
    { "MessageChannel" : "channel1", "ConversationID" : "22222" },
    { "MessageChannel" : "channel1", "ConversationID" : "22222" },
    { "MessageChannel" : "channel2", "ConversationID" : "11111" },
    { "MessageChannel" : "channel2", "ConversationID" : "11111" },
    { "MessageChannel" : "channel2", "ConversationID" : "33333" },
    { "MessageChannel" : "channel2", "ConversationID" : "44444" }
  ]
};

function getConversationsByChannel (data, filterValue) {
  // Note: Omit filterValue to process all channels
  
  const channels = {};
  
  // Loops through the data to build the `channels` object
  data.jsonarray.forEach(item => {
    const channel = item.MessageChannel, id = item.ConversationID;
    
    // Makes sure there is no filter, or channel matches filter, before proceeding
    if(!filterValue || filterValue == channel){
      if(!channels[channel]){
      
        // Adds a property to the `channels` object.
        // Its value is an array including one item: the ConversationID.
        channels[channel] = [id];
      }
      else if(!channels[channel].includes(id)){

        // Add a new ConversationID to the array for this channel
        channels[channel].push(id);
      }
    }
  });
  
  // Replaces the property's value with a number
  //   indicating the number of unique conversations
  for(channel in channels){
              // Uses `for...in` to loop through object properties
    channels[channel] = channels[channel].length;
  }
  
  // Returns the `channels` object
  return channels;
};

console.log("Count of conversations for all channels:");
console.log(getConversationsByChannel(transcriptsData));
// Logs { "channel1": 2, "channel2": 3 }

console.log("Count of conversations for 'channel1' only:");
console.log(getConversationsByChannel(transcriptsData, "channel1"));
// Logs { "channel1": 2 }

Upvotes: 1

Chris HG
Chris HG

Reputation: 1492

Something like:

var transcriptsData = {
    "jsonarray": [
        {"Type":"trace","MessageID":"aHEeHB0t0hHr7175E07zF8kfVjGLBRMdzD_oYUEHNE71Va3wN0yJv9aBAzkOk6JMZvTBRMzBNCUjCvTRuxrAVA","MessageTime":"2019-08-07T09:19:45.342Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Symptoms","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"What are the symptoms of schizophrenia?\"]","Answer":"🙊\nThe symptoms of schizophrenia are usually classified into:\n\n* Positive symptoms – any change in behaviour or thoughts, such as hallucinations or delusions\n* Negative symptoms – a withdrawal or lack of function that you would not usually expect to see in a healthy person; for example, people with schizophrenia often appear emotionless and flat","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":150,\"qna\":null,\"displayText\":\"Related Issues\"}]"}
        ,{"Type":"trace","MessageID":"hLgPSyBP-cAPdKYJ-bFHUckfVjGLBRMdzD_oYUEHNE4bJsq-K4GZvHL9m6guIMtShXFRY-XoxTMdZVBLLZBGDQ","MessageTime":"2019-08-07T09:19:39.582Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Schizophrenia","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"What is schizophrenia?\"]","Answer":"🤔\nViews on schizophrenia have changed over the years. Lots of people question whether it's really a distinct condition, or actually a few different conditions that overlap. But you may still be given this diagnosis if you experience symptoms such as:\n\n* psychosis (such as hallucinations or delusions)\n\n* disorganised thinking and speech\n\n* feeling disconnected from your feelings\n\n* difficulty concentrating\n\n* wanting to avoid people\n\n* a lack of interest in things\n\n* not wanting to look after yourself.\n\nBecause psychiatric experts disagree about what schizophrenia is, some people argue that this term shouldn't be used at all. Others think the name of the condition doesn't matter, and prefer to just focus on helping you manage your symptoms and meeting your individual needs.","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":147,\"qna\":null,\"displayText\":\"Prevalence\"},{\"displayOrder\":0,\"qnaId\":148,\"qna\":null,\"displayText\":\"Causes\"},{\"displayOrder\":0,\"qnaId\":149,\"qna\":null,\"displayText\":\"Symptoms\"},{\"displayOrder\":0,\"qnaId\":150,\"qna\":null,\"displayText\":\"Related Issues\"}]"}
        ,{"Type":"trace","MessageID":"893qgqa3cR9","MessageTime":"2019-08-07T09:19:27.853Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"WHAT_IS_MENTAL_HEALTH","MessageRecipientID":"530667464425015","QuickReplyDisplayText":"Mental Health","QuickReplyPayload":"WHAT_IS_MENTAL_HEALTH","Question":"[\"What is mental health?\"]","Answer":"🤔\nIn many ways, Mental Health is just like Physical Health: Everybody has it and we need to take care of it.\n\nGood Mental Health means being generally able to think, feel and react in the ways that you need and want to live your life. But if you go through a period of poor Mental Health you might find the ways you're frequently thinking, feeling or reacting become difficult, or even impossible, to cope with. This can feel just as bad as a physical illness, or even worse.\n\nMental Health problems affect around one in four people in any given year. They range from common problems, such as depression and anxiety, to rarer problems such as schizophrenia and bipolar disorder.","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":123,\"qna\":null,\"displayText\":\"What Types Are There?\"}]"}
        ,{"Type":"trace","MessageID":"V2VFDEjUb_w3uoJwMwdHYckfVjGLBRMdzD_oYUEHNE7ufPEJdVsZzedQSKsLniMtd9-f_Ngy-mk-tNd1w3X33w","MessageTime":"2019-08-07T09:19:57.637Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Suicide","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"How common is suicide?\"]","Answer":"🤓\nApproximately 6.7% of people have attempted suicide during their lifetime in the UK","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":195,\"qna\":null,\"displayText\":\"Get Help\"}]"}
        ,{"Type":"trace","MessageID":"V2VFDEjUb_w3uoJwMwdHYckfVjGLBRMdzD_oYUEHNE7ufPEJdVsZzedQSKsLniMtd9-f_Ngy-mk-tNd1w3X33w","MessageTime":"2019-08-07T09:19:57.637Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Suicide","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"How common is suicide?\"]","Answer":"🤓\nApproximately 6.7% of people have attempted suicide during their lifetime in the UK","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":195,\"qna\":null,\"displayText\":\"Get Help\"}]"}
        ,{"Type":"trace","MessageID":"RLOUlqwIcO4zSY4zHgWG78kfVjGLBRMdzD_oYUEHNE7gRJSePak9st7_nIIgw3OWXLvAMm4hMXeJ5kFnlIavpQ","MessageTime":"2019-08-07T09:20:04.294Z","MessageChannel":"facebook","MessageSenderID":"2826538590752448","MessageSenderName":"Sean Betts","ConversationID":"2826538590752448-530667464425015","MessageText":"Get Help","MessageRecipientID":"530667464425015","QuickReplyDisplayText":null,"QuickReplyPayload":null,"Question":"[\"Help me\"]","Answer":"\nBeing in a crisis can be very frightening. If you are worried about your safety, thinking of self-harm or feeling suicidal please get some help and support ASAP.\n\nWhen you're in a criss due to Mental Health problems or struggling to deal with your NeuroDiversity it can be difficult to know what to do. Everyone is deserving of support and it's vitally important that you get some when in crisis.\n\nPlease follow this link for details of where you can get help:\n\nhttps://www.mihnd.co.uk/crisis","FollowUpPrompts":"[{\"displayOrder\":0,\"qnaId\":196,\"qna\":null,\"displayText\":\"Help Yourself\"}]"}
    ]
};

var groupBy = function(arr, prop) {
  return arr.reduce(function(groups, item) {
    const val = item[prop]
    groups[val] = groups[val] || []
    groups[val].push(item)
    return groups
  }, {})
}

var conversationsByChannel = function () {
    var conversations = groupBy(transcriptsData.jsonarray,'MessageChannel');
    for (var p in conversations) {
      conversations[p] = conversations[p].length;
    }
    return conversations;
};

console.log(conversationsByChannel());

Upvotes: 2

Related Questions