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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49215358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:19:49  来源:igfitidea点击:

Checking for duplicate strings in JavaScript array

javascriptarrayscompare

提问by Bengall

I have JS array with strings, for example:

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

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

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

I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string.

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

I was trying to compare it with forloop, but I don't know how to write code so that array checks it`s own strings for duplicates, without already pre-determined string to compare.

我试图将它与for循环进行比较,但我不知道如何编写代码以便数组检查它自己的字符串是否有重复项,而无需预先确定要比较的字符串。

回答by Mike Ezzati

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

findDuplicates 函数将数组中所有项的索引与同一项第一次出现的索引进行比较,如果索引不同,则将其作为重复项返回。

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

回答by Kamil Naja

Using ES6 features

使用 ES6 特性

function checkIfDuplicateExists(w){
    return new Set(w).size !== w.length 
}
console.log(
    checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);
console.log(
    checkIfDuplicateExists(["a", "b", "c"]))
//false

回答by kshetline

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

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

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

我在你的原件中添加了另一个副本,只是为了表明它会找到一个非连续的副本。

回答by Halil Azyikmis

Using somefunction 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);
    });
}

回答by Peter Walser

The following code uses a unique-filter(checks if every occurrence of an item is the first occurence) to compare the number of unique items in an array with the total number of items: if both are equal, the array only contains unique elements, otherwise there are some duplicates.

以下代码使用唯一过滤器(检查项目的每次出现是否都是第一次出现)将数组中唯一项目的数量与项目总数进行比较:如果两者相等,则数组仅包含唯一元素,否则有一些重复。

var firstUnique = (value, index, array) => array.indexOf(value) === index;
var numUnique = strArray.filter(firstUnique).length;
var allUnique = strArray.length === numUnique; 

回答by V?n Quy?t

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");
            }
        }
    }
}

回答by Naveed Ali

   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);

         }

    });

回答by Nina Scholz

You could take a Setand filter the values who are alreday seen.

您可以使用 aSet并过滤已经看到的值。

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);

回答by Taylor Austin

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!

这样你就可以对重复的值做任何你想做的事!

回答by Eve

Simple Javascript (if you don't know ES6)

简单的 Javascript(如果你不懂 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 !')
}