At last week's WeAreDevelopers LIVE Day, all about DevOps, we released a new CODE100 challenge!
The Challenge
This time, we gave you a whole load of data containing items that you might find inside of a lunchbox; think fruits, vegetables, prepared foods, and more.
We then provided you with a long list of children, each with their own lunchbox, with all kinds of food inside. Your challenge was to write a script that would return:
- childrenWithoutVeggies: the number of children that have no vegetables
- childrenWithDessert: the number of children that have Sweets & Desserts
- namesWithPreparedFood: an array of names of children with prepared food (sorted alphabetically)
- averageAgeWithPreparedFood: the average age of the children with prepared food
A Solution
Of course, there are many ways you could solve the issue, but below we explain how we did it.
- We used NodeJS, to parse the data as JSON so we could manipulate it (pretty important, right?).
- Next, we iterated over each of the lunchboxes with a forEach loop. Inside of this loop, we manipulate our data slightly, to make it easier to work with. On each iteration, we create a new object called counted, where we sort each of the items in the child’s lunchbox into different categories, and count them for that child in particular. This will make it much easier for us to work with our data in the next step.
- We create an object called result, where - you guessed it - we’re going to store our results.
- To find childrenWithoutVeggies, we can run a simple filter method, returning only children for whom the counted[‘Vegetables’] property is zero. We can then do something similar, to find childrenWithDessert, filtering over our data and only returning those for whom counted[‘Sweets & Desserts’] is greater than zero.
- We then adopt the same approach for finding ‘Prepared Foods’, going one step further, however storing the array of children with prepared foods in a preparedFood variable, which is then sorted by the names of the children, to make sure it's alphabetical.
- Finally, to find the averageAgeWithPreparedFood, we run a reduce function where we divide the ages of the children by the number of children who had prepared food. That’s all there is to it!
We had quite a few submissions and a Math.random() on them all came up with two winners who will move on to the CODE100 final in Berlin in July 2025 at the WeAreDevelopers World Congress! These are:
Marvin Rühe and Robert Glowka
See you next time!