Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
trouble with iterating through values in key/value pairs

I wrote a function that searches through the values of an object. The key is returned when it's confirmed that the key matches the index of the value stored in the array.

eg. 19 is in index 0 in the array, and in the object, the key for 19 is 0. Since this matches, the key is returned.

However, if the value is found in the object but the index is wrong in the array, -2 is returned. Finally, when a value is not found in the object, -1 is returned.

Unfortunately, my function is not working as intended. I had a feeling the function is not recognising the values in the object as the same data type as those in the array so I used == instead of === for the comparisons but the result is the same.

const exampleObject = {
   0: 19,
   1: 20,
   2: 21,
   3: 22
};


function getKey(array, object, value) {
    for (const prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (object[prop] === value && array[object[prop]] == value ){
              return prop
            }
            else if (object[prop] === value && array[object[prop]] !== value ){
              return -2
            }
        }
    }
    return -1
}

console.log(getKey([19,20,22,21],exampleObject,20)) //returns -2 which is wrong as the index is correct

console.log(getKey([19,20,22,21],exampleObject,25)) //returns -1 which is correct

console.log(getKey([19,20,22,21],exampleObject,22)) //returns -2 which is correct

console.log(getKey([19,20,22,21],exampleObject,19)) //returns -2 which is wrong as the index is correct

Edit: I used the code from this site and adjusted it a little: https://www.geeksforgeeks.org/how-to-get-a-key-in-a-javascript-object-by-its-value/

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You just need to use array[prop] instead of array[object[prop]] as object[prop] will return the value but you want the key.

const exampleObject = {
  0: 19,
  1: 20,
  2: 21,
  3: 22
};

function getKey(array, object, value) {
  for (const prop in object) {
    if (object.hasOwnProperty(prop)) {
      if (object[prop] === value && array[prop] === value) {
        return prop
      } else if (object[prop] === value && array[prop] !== value) {
        return -2
      }
    }
  }
  return -1
}

console.log(getKey([19, 20, 22, 21], exampleObject, 20))
console.log(getKey([19, 20, 22, 21], exampleObject, 25))
console.log(getKey([19, 20, 22, 21], exampleObject, 22))
console.log(getKey([19, 20, 22, 21], exampleObject, 19))

about 4 years ago · Juan Pablo Isaza Denunciar

0

If your object always uses 0 - n as keys, this can be simplified quite a bit.

So, let's assume that the object always has numeric keys, starting at 0, incrementing by 1.

In that case, we can define a helper array, which contains all the values of the object like so:

const exampleObjectValues = Object.values(exampleObject);

Now, we can create a simple function using the following logic;

  1. If exampleObjectValues does not contain value, return -1
  2. Otherwise,
    1. Get the index from the input array
    2. Get the index from the exampleObjectValues
    3. Compare them and:
      1. If they match, return the objectValueIndex (step 2.1)
      2. If they don't match, return -2

const exampleObject = {
   0: 19,
   1: 20,
   2: 21,
   3: 22
};
const exampleObjectValues = Object.values(exampleObject);

function getKey(array, value) {
    if (!exampleObjectValues.includes(value)) {
      return -1;
    } else {
      const arrayIndex = array.indexOf(value);
      const objectValueIndex = exampleObjectValues.indexOf(value);
      return (arrayIndex !== objectValueIndex) ? -2 : objectValueIndex;
    }
}

console.log(getKey([19,20,22,21] ,20)); // 1 
console.log(getKey([19,20,22,21], 25)); // -1 
console.log(getKey([19,20,22,21], 22)); // -2
console.log(getKey([19,20,22,21], 19)); // 0

The above will output:

1
-1
-2
0
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda