JavaScript Distinct Record : How to Get Distinct Record From Array

Adesina Mark
By -
0

get-distinct-record-from-array-in-javascript

 In some cases during development, there may be a need to return unique records from a JavaScript array with duplicate records.


Let's take a look at several ways in which this can be done in JavaScript.


Distinct Record with Set

The JavaScript Set object lets you store unique values of any type, whether primitive values or object references. Let's see how this can be used to get unique record from array.

distinct-record-using-set-javascript

We have used the Set object in the above code to eliminate duplicate values. But this is just array of numbers. Next let's see how this can be done if we have array of objects.


Supposed we have this array of objects

With Array of Objects

distinct-record-using-set-javascript-array-of-object

Distinct Record using Map

To get distinct record from an array in JavaScript, we can also loop through the array and store the value to check for in a Map and check against any occurence of the key in other to prevent it from making it to the final results. 

Let's see how this can be done.

distinct-record-using-map-javascript-array

With Array of Objects

distinct-record-using-map-javascript-array-of-object

Distinct Record using Array.prototype.reduce()

Let's see how distinct objects can be returned from array of objects using Array.prototype.reduce() method.

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

distinct-record-using-reduce-javascript-array-of-object

Conclusion

That is it!. If you have some other solutions to this same problem, kindly share it with me. Happy Coding!



Post a Comment

0Comments

Post a Comment (0)