Bengall
Bengall

Reputation: 1417

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 its own strings for duplicates, without already pre-determined string to compare.

Upvotes: 120

Views: 315498

Answers (13)

Eve
Eve

Reputation: 806

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)) {
  console.log('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 !')
}

Upvotes: 2

Mike Ezzati
Mike Ezzati

Reputation: 3166

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", "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

Upvotes: 185

kshetline
kshetline

Reputation: 13682

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

Upvotes: 34

J.E.C.
J.E.C.

Reputation: 3012

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.

Upvotes: 2

Faveren Caleb
Faveren Caleb

Reputation: 21

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

Upvotes: 1

Kamil Naja
Kamil Naja

Reputation: 6692

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

Upvotes: 161

Abdullah Ismail
Abdullah Ismail

Reputation: 465

 const isDuplicate = (str) =>{
   return new Set(str.split("")).size === str.length;
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

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

Upvotes: 12

Berke Kaan Cetinkaya
Berke Kaan Cetinkaya

Reputation: 828

This is the simplest solution I guess :

function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

Upvotes: 0

Taylor Austin
Taylor Austin

Reputation: 5987

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!

Upvotes: -1

Naveed Ali
Naveed Ali

Reputation: 369

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

         }

    });

Upvotes: 1

Văn Quyết
Văn Quyết

Reputation: 2526

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

Upvotes: 0

Halil Azyikmis
Halil Azyikmis

Reputation: 149

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

Upvotes: 11

Related Questions