Given an Array of Integers consisting of n elements with repeated elements, the task is to print all the distinct elements of the array using JavaScript. We can get the distinct elements by creating a set from the integer array.
Examples:
Input : arr = [ 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9 ] Output : [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] Explanation: The input array consist of 4 repeating integers and they are: 4, 5, 7, and 9. After removal of the duplicates elements final array will be: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] Input : arr = [ 4, 4, 4, 4, 4 ] Output : [ 4 ]
Methods to Print All Distinct Elements of a Given Array of Integer
- Using Set Constructor with Spread Operator
- Using Array forEach() and include() Methods
JavaScript Program to Print Distinct Elements using Set Constructor with Spread Operator
An easy solution for the above problem is to create a set object from the elements of the array as a set contains only distinct elements. Then use the Spread Operator ( … ) on the set to form a new array and then print the array.
Example: In this example, we will create new set object from arrray by iterating using spread operator.
Javascript
// Given array const arr = [1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9]; // Creating new array with Distinct elements const distinctArr = [... new Set(arr)]; // Display output console.log(distinctArr); |
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
JavaScript Program to Print Distinct Elements using Array forEach() and include() Methods
We can also solve this problem by using forEach() loop on the input array and include() method to check distinct values.
- Create an empty array.
- Iterate over the array using forEach loop and specify a parameter ‘num’ .
- Check if the distinct array doesn’t contain the current element of the input array (num), only then push the current element on the distinct array.
- Print the distinct array.
Example: In this example, we will use array.forEach and include methods to get distinct array.
Javascript
// Create an array with duplicate elements const arr = [1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9]; // Create an empty array const distinctArr = []; // Using forEach() and includes() method // to get the unique elements arr.forEach((num) => { if (!distinctArr.includes(num)) { distinctArr.push(num); } }); console.log(distinctArr); |
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]