How should I make a function that loops through an array, and checks if any elements are equal
Example:
JavaScript
x
3
1
[a, b, c, d] //false
2
[a, b, a, d] //true
3
EDIT:
I want to use it with nested arrays, like so:
JavaScript
1
3
1
const a = [[1,2,3],[4,5,6]] //false
2
const b = [[1,2,3],[4,5,1]] //true
3
EDIT again: I want the nested arrays to be the exact same
JavaScript
1
4
1
const a = [[1,2],[4,5]] //false
2
const b = [[1,2],[1,2]] //true
3
const c = [[1,2][3,4][1,2]] //true
4
Advertisement
Answer
You can easily do this using Set
as:
JavaScript
1
2
1
const getResult = (arr) => new Set(arr).size !== arr.length;
2
You can add all elements to set and then compare size
of set
and length
of arr
.
You will get different length if any element is repeated else same
JavaScript
1
6
1
const arr1 = ['a', 'b', 'c', 'd']; //false
2
const arr2 = ['a', 'b', 'a', 'd']; //true
3
4
const getResult = (arr) => new Set(arr).size !== arr.length;
5
console.log(getResult(arr1));
6
console.log(getResult(arr2));
If you want to use nested array then you can flat it before seinding arguments
to getResult
function as:
JavaScript
1
12
12
1
const a = [
2
[1, 2, 3],
3
[4, 5, 6],
4
]; //false
5
const b = [
6
[1, 2, 3],
7
[4, 5, 1],
8
]; //true
9
10
const getResult = (arr) => new Set(arr).size !== arr.length;
11
console.log(getResult(a.flat()));
12
console.log(getResult(b.flat()));