If you are new to programming, one really important concept you need to master is the concept of immutable collections. It is a good practice to never modify the original collection you are working with. If you need to filter or modify a collection, rather than modifying the original collection, it is considered better practice to save the changes into a new array. If you are new to programming this concept might sound strange. A lot of coders like to write 'clean code' and creating a new collection when it is not needed can be seen as wasteful, or even counter-productive
The reason why you should not mutate a collection (fancy word for modify) is that it significantly reduces the chances of bugs occurring. When you create a new collection, it will also make your unit tests easier to write. If you mutate your collection during execution, it can be really difficult to try and spot bugs. If you want to learn a little more about this concept, I suggest you read this article for some extra information.
Iterating through an array is the most common way you will deal with collections of data. You can tell when you are working with an array in JSON as it will be wrapped in square brackets, like so
slicer() can all be used. Some of these in-build functions will modify the existing collection while others will not. We know we do not want to modify the existing collection, so which ones should we use?
While iterating through collections
reduce() are all safe. When working with collections try to favour these three as it will result in safer code. Understanding these three functions is an important step towards being able to write clean, functional code.
Sometimes you may need to deal with a collection of objects rather than a collection of arrays, like so:
When dealing with an object, you cannot use the array methods. Instead, you need to use
object.keys to get the name of each objection in the collection. After you have all the
keys within the collection, you can then do a
forEach() using the key to get the data you need. This can be achieved like this:
When dealing with objects you should always use the spread operator to ensure you do not modify the original item. In the code below, we create a clone we can work on rather than modifying the original data: