You have 3 standalone variables with similar functionality. Consider using an object or an array instead, stored in a single variable. Then you can use array methods on the array to sort and retrieve the ordered counts, eg:
const counts = {
apples: 1,
oranges: 4,
bananas: 2,
};
const sortedEntries = Object.entries(counts).sort((a, b) => a[1] - b[1]);
for (const entry of sortedEntries) {
console.log(entry);
}
With the above, to change a particular count, just do something like counts.apples = 5
.
Or, using the array method from the beginning:
const fruits = [
{ name: 'apple', count: 1 },
{ name: 'orange', count: 4 },
{ name: 'banana', count: 2 },
];
const sortedFruits = fruits.sort((a, b) => a.count - b.count);
for (const fruit of sortedFruits) {
console.log(fruit);
}
To change the count of an object in the above array, either .find
the object with the name
you want and assign to its count
property:
fruits.find(({ name }) => name === 'apple').count = 10;
Or create an object like above, mapping each fruit name to its object.