Search code examples
javascriptarraysfunctionobjectlogic

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

Solution

  • in any case your function cann't return a Yes with your actual arguments values.

    I think you are looking for Object.values() ?

    console.log( yOrN( [98887432, 12345890]) );
    
    function yOrN(phone) 
      {
      const temp = [];
      
      for (let el of phone.map(String))
        {
        let res = 'Yes';
        if (el.length > 10)
          res = 'No';
        else
          {
          let tempObj = [...el].reduce((a,c)=> ( a[c] ??= 0, a[c]++, a), {})
          if ( Object.values(tempObj).some( v => v < 3 || v > 4)) 
            res = 'No';
    
          console.log( res, JSON.stringify( tempObj ))  
          }
        temp.push(res);
        }
      return temp;
      }