查找 js 数组中的重复元素
有几种方法可以计算 JavaScript 数组中的重复元素。使用forEach
或for
循环。
声明空对象
,使用 for 循环遍历数组。
使用数组元素作为键,
如果存在则增加键的值,否则将键初始化为 1
const a = [4,3,6,3,4,3]
function count_duplicate(a){
let counts = {}
for(let i =0; i < a.length; i++){
if (counts[a[i]]){
counts[a[i]] += 1
} else {
counts[a[i]] = 1
}
}
for (let prop in counts){
if (counts[prop] >= 2){
console.log(prop + " counted: " + counts[prop] + " times.")
}
}
console.log(counts)
}
count_duplicate(a)
/* 3 counted: 3 times.
4 counted: 2 times.
{ '3': 3, '4': 2, '6': 1 }
*/
const items2 = ['pencil', 'book','pencil']
function find_duplicate_in_array(array){
const count = {}
const result = []
array.forEach(item => {
if (count[item]) {
count[item] +=1
return
}
count[item] = 1
})
for (let prop in count){
if (count[prop] >=2){
result.push(prop)
}
}
console.log(count)
return result;
}
find_duplicate_in_array(items2)
// {pencil: 2, book: 1}
//[pencil
以下是检查 javascript 数组中重复值的几种方法。
方法 1. 使用对象
JavaScript 对象由键值对组成,其中键是唯一的。如果您尝试添加具有不同值的重复键,则该键的旧值将被新值覆盖。
- 声明一个空对象。
- 使用 for 循环遍历数组。
- 在每次迭代中,在步骤 1 中创建的对象中添加一个新条目,以数组元素作为键并具有一些固定值。
- 检查对象中是否存在以当前数组元素为键的条目。
- 如果某个条目已经存在,则意味着数组中有另一个具有相同值的元素,并终止循环。
checkDuplicate();
function checkDuplicate() {
let arr = ["abc","xy","bb", "axz", "abc"];
// empty object
let map = {};
let result = false;
for(let i = 0; i < arr.length; i++) {
// check if object contains entry with this element as key
if(map[arr[i]]) {
result = true;
// terminate the loop
break;
}
// add entry in object with the element as key
map[arr[i]] = true;
}
if(result) {
console.log('Array contains duplicate elements');
} else {
console.log('Array does not contain duplicate elements');
}
}
在添加之前应该检查条目,否则,它将标记第一个元素的数组重复。
我们添加了一个布尔值 true 作为对象条目的值,但您可以添加任何其他值。在这种情况下,也应该使用添加的相同值进行比较。
您也可以document.write
在 Chrome Dev 中使用。我仅用于测试目的。console.log
console.log
方法 2. 使用集合
在 ES6 中,我们有一个 JavaScript Set 对象,它只存储唯一元素。可以通过直接将数组传递给其构造函数来创建包含数组值的 Set 对象。
如果数组包含重复的值,Set 会将其删除。这意味着 Set 将只包含唯一数组元素。请注意,原始数组不会被修改。
如果我们比较原始数组的长度和使用此数组创建的 Set 对象的长度,发现不匹配,则显然该数组至少包含一个重复项。
此方法的 JavaScript 代码如下所示。
checkDuplicate();
function checkDuplicate() {
let arr = ["abc","xy","bb", "abc"];
let result = false;
// create a Set with array elements
const s = new Set(arr);
// compare the size of array and Set
if(arr.length !== s.size){
result = true;
}
if(result) {
console.log('Array contains duplicate elements');
} else {
console.log('Array does not contain duplicate elements');
}
}
方法3. 比较元素的索引
此方法用于比较数组元素的两个索引:一个是第一个索引,另一个是最后一个索引。
如果两个索引相同,则表示该元素在数组中仅出现一次;如果两个索引不同,则明确表示该元素出现多次,因为同一个元素不能有两个不同的索引。
此方法需要使用 for 循环遍历数组,但只迭代到元素的第一个索引和最后一个索引匹配为止。此时应终止循环。
此方法的 JavaScript 代码如下所示。
checkDuplicate();
function checkDuplicate(){
let arr = ["abc","xy","bb", "abc"];
let result = false;
// iterate over the array
for(let i = 0; i < arr.length;i++) {
// compare the first and last index of an element
if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])){
result = true;
// terminate the loop
break;
}
}
if(result) {
console.log('Array contains duplicate elements');
} else {
console.log('Array does not contain duplicate elements');
}
}
方法 4. 使用一些函数
JavaScript some 函数会检查数组中所有元素是否符合某个条件,如果满足该条件,则返回 true。
待检查的条件作为 some 函数的参数传入。此函数是一个回调函数,它会对每个数组元素逐个调用,并返回 true 或 false。
它会一直调用,直到返回 false,一旦返回 true,就不会再调用。
参数函数接受三个参数:
- value:当前数组元素的值。
- index:提供的数组元素的索引。
- 数组:数组本身。
逻辑
在参数回调函数中,我们将当前数组元素作为第一个参数,并将当前元素的索引作为第二个参数。
现在,我们使用 indexOf 函数获取数组元素的第一个索引,并将其与第二个参数提供的索引进行比较。
如果索引匹配,则表示该数组元素仅出现一次。如果索引不匹配,则认为该元素出现多次
。下面给出了一个使用函数检查重复数组元素的 Javascript 程序。
checkDuplicate();
function checkDuplicate() {
let arr = ["abc","xy","bb", "abc"];
let result = false;
// call some function with callback function as argument
result = arr.some((element, index) => {return arr.indexOf(element) !== index});
if(result) {
console.log('Array contains duplicate elements');
} else {
console.log('Array does not contain duplicate elements');
}
}
方法 5. 使用迭代
将数组中的每个元素与所有其他元素进行比较,以测试它是否与任何其他元素匹配。如果找到匹配项,则表示该数组包含重复元素。
此方法需要一个嵌套循环,其中外层循环将遍历数组元素,内层循环将每个元素与剩余元素进行比较。
一旦找到匹配项,立即终止两个循环。
此方法的 JavaScript 代码如下。
checkDuplicate();
function checkDuplicate(element, index) {
let arr = ["abc","xy","bb", "abc"];
for(let i = 0; i < arr.length;i++) {
// nested loop
for(let j = 0; j < arr.length;j++) {
// do not compare same elements
if(i !== j) {
// check if elements match
if(arr[i] === arr[j]){
// duplicate element found
result = true;
// terminate inner loop
break;
}
}
}
// terminate outer loop
if(result){
break;
}
}
if(result) {
console.log('Array contains duplicate elements');
} else {
console.log('Array does not contain duplicate elements');
}
}
参考
https://codippa.com/how-to-check-if-array-contains-duplicate-values-in-javascript/