Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

325
Views
Is there a way to return a conditional object value and key?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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]))

about 4 years ago · Juan Pablo Isaza Report

0

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]))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!