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 increment the obj key?

i was trying to find a same number in a string, but the obj key wasnt want to increment the value, and its still readed as a negation

function yOrN(phone) {
  const temp = [];
  for (let i = 0; i < phone.length; i++) {
    const el = String(phone[i]);
    if (el.length > 10) {
      temp.push("No");
      break;
    }
    let tempObj = {};
    for (let j = 0; j < el.length; j++) {
      const em = el[j];
      if (!tempObj[el[j]]) {
        tempObj[el[j]] = 0;           //! this side make me stucked rn
      } else if (tempObj) {
        tempObj[el[j]] = tempObj[el[j]] + 1;
      }
    }
    for (const num in tempObj) {
      if (tempObj[num] < 3 || tempObj[num] > 4) {
        temp.push("No");
        break;
      } else {
        temp.push("Yes");
        break;
      }
    }
  }
  return temp;
}
console.log(yOrN([98887432, 12345890]));

the expected output was ["yes", "no"] 🙁
and its still ["no", "no"]

{ '2': 1, '3': 1, '4': 1, '7': 1, '8': 5, '9': 1 } for the index 0
{ '0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '8': 1, '9': 1 } for the index 1

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 :

It looks like you are trying to count the occurrences of each number in the el array and store the counts in the tempObj object.

To achieve this, you can use the following code:

let tempObj = {};
for (let j = 0; j < el.length; j++) {
  const em = el[j];
  if (!tempObj[em]) {
    tempObj[em] = 1;
  } else {
    tempObj[em]++;
  }
}

This will correctly increment the value of the em key in the tempObj object each time the same number is found in the el array.

The output of this code will be an object with keys for each number in the el array, and the corresponding value will be the number of occurrences of that number in the array. For example, if the el array contains the numbers [0, 1, 2, 3, 4, 5, 8, 9], the output will be { ‘0’: 1, ‘1’: 1, ‘2’: 1, ‘3’: 1, ‘4’: 1, ‘5’: 1, ‘8’: 1, ‘9’: 1 }.

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