[javascript] Checking for duplicate strings in JavaScript array

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.

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.

This question is related to javascript arrays compare

The answer is


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

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

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


Here's my solution if you are using typescript in a functional way:

const hasDuplicates = <T>(arr: T[]): boolean => {
  if (arr.length === 0) return false
  if (arr.lastIndexOf(arr[0]) !== 0) return true
  return hasDuplicates(arr.slice(1))
}

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

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.

Updated version with arrow function:

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

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

I think it can't be simpler than this.

_x000D_
_x000D_
const findDuplicates = arr => [...new Set(arr.filter(v => arr.indexOf(v) !== arr.lastIndexOf(v)))];

console.log(findDuplicates([ "q", "w", "w", "e", "i", "u", "r"]));
_x000D_
_x000D_
_x000D_


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

_x000D_
_x000D_
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 !')
}
_x000D_
_x000D_
_x000D_

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 !')
}

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; 

   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 can do this using a Set. You have to create a Set and put all the values in your Array, in that Set. Then, you check whether they have the same length or not. If not, you know there are duplicate values, because a Set can only have unique values. It is explained in the link below:

https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c


Using ES6 features

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to compare

Checking for duplicate strings in JavaScript array How to compare two files in Notepad++ v6.6.8 How to compare LocalDate instances Java 8 Comparing the contents of two files in Sublime Text comparing elements of the same array in java How to compare two dates along with time in java bash string compare to multiple correct values Query comparing dates in SQL How to compare two java objects Comparing two integer arrays in Java