检查 JavaScript 数组中的重复字符串

我有一个带字符串的 JS 数组,例如:

var strArray = [ "q", "w", "w", "e", "i", "u", "r"];

我需要比较重复的字符串内的数组,如果重复的字符串存在,应该有警报框指向该字符串。

我试图将其与 for循环进行比较,但我不知道如何编写代码,以便在没有预先确定的字符串进行比较的情况下,数组检查自己的字符串是否有重复。

240709 次浏览

The findDuplicates function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.

let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)


console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates

    var strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
var alreadySeen = {};
  

strArray.forEach(function(str) {
if (alreadySeen[str])
console.log(str);
else
alreadySeen[str] = true;
});

I added another duplicate in there from your original just to show it would find a non-consecutive duplicate.

Updated version with arrow function:

const strArray = [ "q", "w", "w", "e", "i", "u", "r", "q"];
const alreadySeen = {};
  

strArray.forEach(str => alreadySeen[str] ? console.log(str) : alreadySeen[str] = true);

Using ES6 features

  • Because each value in the Set has to be unique, the value equality will be checked.

function checkIfDuplicateExists(arr) {
return new Set(arr).size !== arr.length
}
  

var arr = ["a", "a", "b", "c"];
var arr1 = ["a", "b", "c"];


console.log(checkIfDuplicateExists(arr)); // true
console.log(checkIfDuplicateExists(arr1)); // false

Using some function on arrays: If any item in the array has an index number from the beginning is not equals to index number from the end, then this item exists in the array more than once.

// vanilla js
function hasDuplicates(arr) {
return arr.some( function(item) {
return arr.indexOf(item) !== arr.lastIndexOf(item);
});
}

function hasDuplicates(arr) {
var counts = [];


for (var i = 0; i <= arr.length; i++) {
if (counts[arr[i]] === undefined) {
counts[arr[i]] = 1;
} else {
return true;
}
}
return false;
}


// [...]


var arr = [1, 1, 2, 3, 4];


if (hasDuplicates(arr)) {
alert('Error: you have duplicates values !')
}

Simple Javascript (if you don't know ES6)

function hasDuplicates(arr) {
var counts = [];


for (var i = 0; i <= arr.length; i++) {
if (counts[arr[i]] === undefined) {
counts[arr[i]] = 1;
} else {
return true;
}
}
return false;
}


// [...]


var arr = [1, 1, 2, 3, 4];


if (hasDuplicates(arr)) {
alert('Error: you have duplicates values !')
}

Use object keys for good performance when you work with a big array (in that case, loop for each element and loop again to check duplicate will be very slowly).

var strArray = ["q", "w", "w", "e", "i", "u", "r"];


var counting = {};
strArray.forEach(function (str) {
counting[str] = (counting[str] || 0) + 1;
});


if (Object.keys(counting).length !== strArray.length) {
console.log("Has duplicates");


var str;
for (str in counting) {
if (counting.hasOwnProperty(str)) {
if (counting[str] > 1) {
console.log(str + " appears " + counting[str] + " times");
}
}
}
}
   var elems = ['f', 'a','b','f', 'c','d','e','f','c'];


elems.sort();


elems.forEach(function (value, index, arr){


let first_index = arr.indexOf(value);
let last_index = arr.lastIndexOf(value);


if(first_index !== last_index){


console.log('Duplicate item in array ' + value);


}else{


console.log('unique items in array ' + value);


}


});

You could take a Set and filter to the values that have already been seen.

var array = ["q", "w", "w", "e", "i", "u", "r"],
seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));


console.log(seen);

You could use reduce:

const arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
if(acc[cur]) {
acc.duplicates.push(cur)
} else {
acc[cur] = true //anything could go here
}
}, { duplicates: [] })

Result would look like this:

{ ...Non Duplicate Values, duplicates: ["w"] }

That way you can do whatever you want with the duplicate values!

This is the simplest solution I guess :

function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
 const isDuplicate = (str) =>{
return new Set(str.split("")).size === str.length;
}

You have to create an empty array then check each element of the given array if the new array already has the element it will alert you. Something like this.

  var strArray = [ "q", "w", "w", "e", "i", "u", "r"];
let newArray =[];
function check(arr){
for(let elements of arr){
if(newArray.includes(elements)){
alert(elements)
}
else{
newArray.push(elements);
}
}
return newArray.sort();
}
check(strArray);
function hasDuplicateString(strings: string[]): boolean {
const table: { [key: string]: boolean} = {}
for (let string of strings) {
if (string in table) return true;
table[string] = true;
}
return false
}




Here the in operator is generally considered to be an 0(1) time lookup, since it's a hash table lookup.