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

查看:87
本文介绍了检查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 it`s own strings for duplicates, without already pre-determined string to compare.

推荐答案

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

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.

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天全站免登陆