Reputation: 11
I'm defining a function that returns a list of the keys which are paired with that value in the dictionary.
I can get the first key to be printed, but it will not print the second one or beyond. I know I should put in a list but I can't figure out to get that working.
dict1 = {'cat' : 1, 'dog': 3, 'bird':4,'lizard':4,'hamster': 5 };
function keyList(dict, value) {
for(x in dict)
if(dict[x] == value)
return x;
}
console.log(keyList(dict1, 4));
When I run the current program I just get bird. I want the code to return both bird and lizard.
Upvotes: 0
Views: 59
Reputation: 1973
Just iterate through the keys and filter the ones out where its value doesn't equal your passed value.
dict1 = {'cat' : 1, 'dog': 3, 'bird':4,'lizard':4,'hamster': 5 }
function keyList(dict, value) {
return Object.keys(dict).filter(x => dict[x] === value);
}
console.log(keyList(dict1, 4))
Upvotes: 4
Reputation: 2338
You could try something this. There may be a filter function that does something similar:
dict1 = {'cat' : 1, 'dog': 3, 'bird':4,'lizard':4,'hamster': 5 }
function getPropertiesByValue(object, value) {
Object.keys(object).forEach(key => {
if (object[key] != value ) delete object[key];
});
return object;
}
alert(JSON.stringify(getPropertiesByValue(dict1, 4)));
Upvotes: 0
Reputation: 21672
You could use Object.keys()
to get an object's keys as an array (e.g. ["cat", "dog", "bird", "lizard", "hamster"]
).
Array.filter()
then allows you to specify which items to keep.
In your case, you want to keep "Keys whose value is 4", hence obj[key] === value
.
const dict1 = {'cat' : 1, 'dog': 3, 'bird':4,'lizard':4,'hamster': 5 };
const keyList = (obj, value) => Object.keys(obj).filter(key => obj[key] === value);
console.log( keyList(dict1,4) );
Upvotes: 1
Reputation: 15847
Instead of immediately returning, push the value to an array then return the array
dict1 = {'cat' : 1, 'dog': 3, 'bird':4,'lizard':4,'hamster': 5 }
function keyList(dict, value) {
let keys = [];
for(x in dict)
if(dict[x] == value){keys.push(x);}
return keys;
}
console.log(keyList(dict1, 4))
Upvotes: 1