Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a str2 can be made from str1 using objects

I’ve been struggling to find out how to return false when the count goes below 0, tried playing with the 2nd loop, however I don’t know how to stop the count as soon as it reaches 0

let char = {}

function charCount(str1, str2) {
  str1 = str1.toLowerCase()
  str2 = str2.toLowerCase()

  for (i = 0; i < str1.length; i++) {
    if (str1[i] in char) {
      char[str1[i]]++
    } else {
      char[str1[i]] = 1
    }
  }

  for (i = 0; i < str2.length; i++) {
    // Error is found here
    if (str2[i] in char) {
      char[str2[i]]--
    } else {
      return false
    }
  }
  console.log(char)
  return true
}
console.log(charCount("hello", "helllo"))

Output

{h: 0, e: 0, l: -1, o: 0}
true

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could check if the property has a truthy value , then decrement, otherwise exit the loop with false.

BTW, you should declare varaibles, otherwise you get global variables which may lead to confusions.

function charCount(str1, str2) {
    let char = {};
    str1 = str1.toLowerCase();
    str2 = str2.toLowerCase();

    for (let i = 0; i < str1.length; i++) {
        if (str1[i] in char) char[str1[i]]++;
        else char[str1[i]] = 1;
    }

    for (let i = 0; i < str2.length; i++) {
        if (char[str2[i]]) char[str2[i]]--;
        else return false;
    }
    return true;
}

console.log(charCount("hello", "helllo"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading