Home > Enterprise >  find the odd value in a javascript object
find the odd value in a javascript object

Time:09-29

I have an object in JavaScript and I would like to find the one value that is an odd number, then return that value's corresponding key. For example:

const myObject = {
                   'a': 4,
                   'b': 6,
                   'c': 7,
                   'd': 8
                  }

From this, I would like to return 'c'. The following is what I have attempted, but I get an error.

const myObject = {
  'a': 4,
  'b': 6,
  'c': 7,
  'd': 8
}
myObject.forEach((i) => {
  if (counts.value[i] % 2 === 0)
    return counts.key[i];
});

CodePudding user response:

You can use Object.keys to get the array of myObject keys and use find to get the value that is odd.

const myObject = {
   'a': 4,
   'b': 6,
   'c': 7,
   'd': 8
}

let key = Object.keys(myObject).find((key) => myObject[key] % 2)

console.log(key)

CodePudding user response:

You can use Array#find on Object.keys.

const myObject = {
  'a': 4,
  'b': 6,
  'c': 7,
  'd': 8
};
const res = Object.keys(myObject).find(k => myObject[k] % 2 !== 0);
console.log(res);

CodePudding user response:

Get object values to array and filter the odd values from the values array

const myObject = { 'a': 4, 'b': 6, 'c': 7, 'd': 8};
const valuesArr = Object.values(myObject);
const result = valuesArr.filter((value) =>  {
   if ((value % 2) !== 0) {
      return value;
   }
});
console.log(result);

CodePudding user response:

Find the result in single iteration and return the odd value key.

const myObject = { 'a': 4, 'b': 6, 'c': 7, 'd': 8};
let result = '';

for(const key in myObject) {
  if((myObject[key] % 2) !== 0) {
      result = key;
      break;
  }
}

console.log(result);
//return result;

CodePudding user response:

  const myObject = {
                       'a': 4,
                       'b': 6,
                       'c': 7,
                       'd': 8
                      };
    Object.keys(myObject).filter((each) => {
    if( myObject[each] % 2 === 1){ 
    return each;
    }
        );
  • Related