Home > Back-end >  Is there a way to return a conditional object value and key?
Is there a way to return a conditional object value and key?

Time:06-19

I am new and learning programming. I wondered if there is a way to get a specific value key or (in this case) key from an object if it passes a condition.

function miti (a){
    let obj = {};
    let num;
    for(let i =0; i < a.length; i  ){
        num = a[i]
        if(obj[num] === undefined){
          obj[num]= 1
        } else {
          obj[num]   
        }
   }
   //Now I have created an object that records the frequancy of each presented number.
   if(Object.values(obj) === 1){
     return 
   }
}
console.log(miti([1,2,1,3,4,3,4,5))

From the above code, I would like to extract a lonely number with no pairs, I built an object that records each frequency from a given array.

Please be a little descriptive since I am a newbie.

CodePudding user response:

Object.values(obj) === 1 doesn't make any sense because Object.values returns an array, which definitely won't be equal to a number.

Iterate through the entries of the object (the key-value pairs) and return the first entry for which the value is 1.

function miti(a) {
  let obj = {};
  let num;
  for (let i = 0; i < a.length; i  ) {
    num = a[i]
    if (obj[num] === undefined) {
      obj[num] = 1
    } else {
      obj[num]  
    }
  }
  for (const entry of Object.entries(obj)) {
    if (entry[1] === 1) {
      return entry[0];
      // or return entry, if you want the whole entry and not just the key
    }
  }
}
console.log(miti([1, 2, 1, 3, 4, 3, 4, 5]))

Or .find the entry matching the condition and return it.

function miti(a) {
  let obj = {};
  let num;
  for (let i = 0; i < a.length; i  ) {
    num = a[i]
    if (obj[num] === undefined) {
      obj[num] = 1
    } else {
      obj[num]  
    }
  }
  return Object.entries(obj)
    .find(entry => entry[1] === 1)
    [0];
}
console.log(miti([1, 2, 1, 3, 4, 3, 4, 5]))

CodePudding user response:

Or, using the Array methods .forEach() and .find() in combination with Object.keys() you can do it like that:

function firstUniqueValue(a) {
  let obj = {};
  a.forEach(k=>obj[k]=(obj[k]||0) 1);
  return Object.keys(obj).find(k=>obj[k]==1);
}
console.log(firstUniqueValue([1, 2, 1, 3, 4, 3, 4, 5]))

  • Related