Arrays Containing Simple Data
- The Set object, which is a collection of values like an array, however, the Set object differs from an array as it is inherently unable to store non-unique values. This makes it an ideal object to use for removing duplicate values.
- The spread operator, written as:
...array. In this use case, the spread operator essentially takes each item in the set and passes it as an item to be added to the array in its internal constructor, so that the resulting array is made up of each item in the Set object.
It is also important to note that the above code will not mutate the original array, meaning that the duplicatesArray constant still contains all the original entities. The unique items are stored separately in a new array.
Arrays Containing Objects with Multiple Properties
This means we need to use a bit more array manipulation logic to identify the objects with the same values.
There are a few different use cases that are going to be the most likely you'll come across:
- A duplicate object is one where a single object property value must be unique
What we are doing here is turning the original array into an array of primitive types by using the .map() function to retrieve only the id property values. By putting this inside a new Set() object, we achieve the same functionality as the first example to create unique values only. The second call of the .map() function then returns the entire object from the original array by finding the element with that id value. The .find() function retruns the first entity in the array that matches the search criteria so we will get the object with the name 'Nick' in this case.
- A duplicate object is one where multiple object property values cannot be equal across objects
In this use case, we are running the sub-function isDuplicate to check whether the array contains an object that has both the id and name properties. If this function returns false, then we add the object to the unique array. If the unique array already contains the object, then we continue.
- All object property values must not be equal across the objects
In this use case, we are using the in-built array filter method and then using a new object to evaluate whether the combined list of object keys exists already. The combined list of object properties is set into the key variable by using Object.keys() which returns an array of the key names. By then mapping this to get the value for each key we then join them into a string in the format of value|value ('1|James|19'). This is then the key we add to the new object if it dows not exist. If it doesn't then we return true to the filter function so it includes the original object in the final array.
If you liked this post, please share it!