检查 JavaScript 数组中的重复字符串 [英] Checking for duplicate strings in JavaScript array

查看:39
本文介绍了检查 JavaScript 数组中的重复字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have JS array with strings, for example:

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.

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

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

推荐答案

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

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

这篇关于检查 JavaScript 数组中的重复字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆