Home > Blockchain >  How to increment the obj key?
How to increment the obj key?

Time:12-21

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

CodePudding user response:

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 }.

  • Related