-2

I have an array, and I want an output if it contains more than 1 of the same element.

Example:

my_array = [1, 2, 3, 1];
k.peter
  • 3
  • 1

2 Answers2

1

if you want a Boolean output if an element is repeated you can do this:

var arr=[1,1,3,4]
let isDup=false;
arr.map(x=>(arr.indexOf(x)!==arr.lastIndexOf(x))?isDup=true:isDup)
console.log(isDup)
Abdelillah Aissani
  • 3,058
  • 2
  • 10
  • 25
0

Convert the array to a Set. A Set can only contain unique values. If the Set's size is less than the array's length, there are duplicates:

const hasDuplicates = (arr) => arr.length > new Set(arr).size;

console.log(hasDuplicates([1, 2, 3])); // false
console.log(hasDuplicates([1, 2, 3, 1])); // true
Ori Drori
  • 183,571
  • 29
  • 224
  • 209