0

My api response looks like this:

id: (...)
user_id: (...)
symptoms: "Sore throat, Headache"

id: (...)
user_id: (...)
symptoms: "Anorexia  (Loss of appetite), Shortness of breath (Difficult in breathing), Myalgias (Muscle pains), Sore throat, Headache"

I am trying to match a users symptoms to existing symptoms categories. A user can have upto 14 symptoms. I keep getting an error of Cannot read property 'slice' of undefined when i split and slice the array to get individual symptoms and match them.

When i try to put a default value for the object if a user has less than 14 symptoms, the error persists.

My code:

getSymNum (symp, c) {
        var counter = 0

      for (var xc in c) {

        var symp1 = c[xc].symptoms.split(',')[0]
        var symp2 = c[xc].symptoms.split(',')[1].slice(1)
        var symp3 = c[xc].symptoms.split(',')[2].slice(2)
        var symp4 = c[xc].symptoms.split(',')[3].slice(3)
        var symp5 = c[xc].symptoms.split(',')[4].slice(4)
        var symp6 = c[xc].symptoms.split(',')[5].slice(5)

        if (symp3 !== undefined){       
        console.log("hello ha")
        
        }

        if (symp1 === symp) {
        counter++
        } else if (symp2 === symp) {
          counter++
        } else if (symp3 === symp)  {
          counter++
        } else if (symp4 === symp) {
          counter++
        } else if (symp5 === symp) {
          counter++
        } else if (symp6 === symp) {
          counter++
        }

      }
      return counter  
      
    },
3
  • I'm not sure I understand; symptoms is a single comma-separated string. Split it once, the array will contain as many elements as there are symptoms. You're currently splitting it over and over and trying to slice each individual string whether or not it exists. Commented Jul 6, 2020 at 14:46
  • Unrelated, but "anorexia" and "loss of appetite" are distinct and not necessarily related. Commented Jul 6, 2020 at 14:47
  • Call c[xc].symptoms.split(',') once, not multiple times. And only access as many elements as are present, for example 2 in your first example. Commented Jul 6, 2020 at 14:49

1 Answer 1

1

You can optimize the check by using array/string methods like contains() or indexOf():

etSymNum (symp, c) {
  var counter = 0

  for (var xc in c) {
    if(c[xc].symptoms.indexOf(symp) !== -1){
      counter++;
    }
  }
  return counter  
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.