1

I'm wondering how the some() method and arrow functions can be used to simplify my duplicate check in JavaScript. This is what I have at the moment (being used in a guessing game):

function guessRepeatValidate(userGuess) {
    let passed = true;
    if (guessArchive.indexOf(userGuess) > -1) {
        passed = false;
    }
    return passed;
}

This has been puzzling me for a while, so it'd be great to see what you folks have in mind to make this work with some().

  • please add the array. your question is unclear. so you want to search for duplicates or just for a single existence? – Nina Scholz Feb 07 '21 at 19:25
  • `some` is sort of like `includes`.. the difference is, `includes` takes in a value, checks through the array, if a value in the array equals the parameter value, return true.. how `some` works is that it takes in a function, it checks through the array(putting in the value of each index as it goes along) and if your function returns `true`.. the condition in the array is met – The Bomb Squad Feb 07 '21 at 19:26
  • Unless this is some sort of homework assignment, it isn't very efficient to use `.some()` to check for duplicates. A classic way to check for duplicates is to use a Set as in [How to see if an array has 2 or more elements that are the same](https://stackoverflow.com/questions/65927471/how-to-see-if-an-array-has-2-or-more-elements-that-are-the-same/65927499#65927499). – jfriend00 Feb 07 '21 at 19:50
  • > please add the array. your question is unclear. so you want to search for duplicates or just for a single existence? Checking for duplicates by utilizing only the .some() function. I probably should've been clearer about that. The array is dynamic and is the input passed into the guessing game from a simple HTML webpage. – Colton Rushton Feb 07 '21 at 20:11

2 Answers2

2

You could take a closure over a Set and return the check if an item exist in the set.

const 
    guessRepeatValidate = userGuess => userGuess.some(
        (s => v => s.has(v) || !s.add(v))
        (new Set)
    );

console.log(guessRepeatValidate([1, 2, 3]));
console.log(guessRepeatValidate([1, 2, 3, 4, 2]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can do it simply by using some with indexOf

const arr = ['a', 'b', 'c', 'a']
const containsDuplicate = arr.some((el, i) => arr.indexOf(el, i+1) > -1)

console.log(containsDuplicate)
Dominik Matis
  • 2,086
  • 10
  • 15