JavaScript Program to Print All Distinct Elements in an Integer Array
Last Updated :
04 Jun, 2024
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);
Output[
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);
Output[
1, 2, 3, 4, 5,
6, 7, 8, 9
]
Method: Using Object Property as Flags
In this approach, we use an object to keep track of whether we have encountered an element or not. We iterate through the array, and for each element, we check if it exists as a property in the object. If it doesn't, we add it to the object and push it into the distinct array.
JavaScript
function printDistinctElements(arr) {
const distinctArr = [];
const encountered = {};
for (let i = 0; i < arr.length; i++) {
if (!encountered[arr[i]]) {
encountered[arr[i]] = true;
distinctArr.push(arr[i]);
}
}
return distinctArr;
}
const arr = [1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9];
const distinctArr = printDistinctElements(arr);
console.log(distinctArr);
Output[
1, 2, 3, 4, 5,
6, 7, 8, 9
]
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read