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/
>Solution :
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))