How can it be done to obtain the largest and smallest number among the properties of an object like the following?
var animales = {
caballos: 10,
perros: 4,
pez_espada: 1,
tortugas: 3,
gatos: 6,
hipopotamos: 4,
elefantes: 4
}
How can it be done to obtain the largest and smallest number among the properties of an object like the following?
var animales = {
caballos: 10,
perros: 4,
pez_espada: 1,
tortugas: 3,
gatos: 6,
hipopotamos: 4,
elefantes: 4
}
You can use the Object.entries methods to get the properties in the form of an array and Array.reduce to get the one with the largest or smallest value.
This way you not only get the highest or lowest values, you also get the name of the property they belong to.
The result that is printed on the console is:
La propiedad con el mayor valor es caballos y su valor es 10
La propiedad con el menor valor es pez_espada y su valor es 1
It can be done this way using
forEach
andObject.keys