Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Javascript check if any elements in array are equal

How should I make a function that loops through an array, and checks if any elements are equal

Example:

[a, b, c, d] //false
[a, b, a, d] //true

EDIT:

I want to use it with nested arrays, like so:

const a = [[1,2,3],[4,5,6]] //false
const b = [[1,2,3],[4,5,1]] //true

EDIT again: I want the nested arrays to be the exact same

const a = [[1,2],[4,5]] //false
const b = [[1,2],[1,2]] //true
const c = [[1,2][3,4][1,2]] //true
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can easily do this using Set as:

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

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

const arr1 = ['a', 'b', 'c', 'd']; //false
const arr2 = ['a', 'b', 'a', 'd']; //true

const getResult = (arr) => new Set(arr).size !== arr.length;
console.log(getResult(arr1));
console.log(getResult(arr2));

If you want to use nested array then you can flat it before seinding arguments to getResult function as:

const a = [
    [1, 2, 3],
    [4, 5, 6],
]; //false
const b = [
    [1, 2, 3],
    [4, 5, 1],
]; //true

const getResult = (arr) => new Set(arr).size !== arr.length;
console.log(getResult(a.flat()));
console.log(getResult(b.flat()));

about 4 years ago · Juan Pablo Isaza Relatório

0

Simplest way would be to loop through the array and check if the first index of the element is same as current index like this:

let a = [1, 2, 3, 4]
let b = [1, 2, 3, 1]
    let isRepeated = (a) => {
      for (let i = 0; i < a.length; i++) {
        if (a.indexOf(a[i]) !== i)
          return true;
      }

      return false;
    }

    console.log(isRepeated(a));
    console.log(isRepeated(b));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda