JavaScript 打印整数数组中的所有不同元素的程序

JavaScript 打印整数数组中的所有不同元素的程序

给定一个由n个元素组成的整数数组,其中可能包含重复元素,任务是使用JavaScript打印数组中的所有不同元素。我们可以通过从整数数组创建一个集合来获取不同的元素。

示例:

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 ]

打印给定整数数组的所有不同元素的方法

  • 使用Set构造函数和展开运算符
  • 使用数组forEach()和include()方法

使用Set构造函数和展开运算符打印不同元素的JavaScript程序

解决以上问题的简单方法是通过数组的元素创建一个 set 对象,因为set只包含不同的元素。然后使用展开运算符 将set转换为一个新数组,然后打印数组。

示例: 在这个例子中,我们将使用展开运算符迭代数组来创建新的set对象。

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
]

使用Array forEach()和include()方法打印不同元素的JavaScript程序

我们也可以通过在输入数组上使用forEach()循环和include()方法来解决这个问题,以检查不同的值。

  • 创建一个空数组。
  • 使用forEach循环迭代数组,并指定一个参数 num
  • 检查不同数组是否不包含当前输入数组的元素(num),只有在这种情况下,将当前元素推入不同的数组。
  • 打印不同的数组。

示例: 在这个示例中,我们将使用array.forEach和include方法来获取不同的数组。

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
]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程