Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Javascript verifica si algún elemento en la matriz es igual

¿Cómo debo hacer una función que recorra una matriz y verifique si algún elemento es igual?

Ejemplo:

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

EDITAR:

Quiero usarlo con matrices anidadas, así:

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

EDITAR nuevamente: quiero que las matrices anidadas sean exactamente iguales

 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 answers
Answer question

0

Puede hacer esto fácilmente usando Set como:

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

Puede agregar todos los elementos al conjunto y luego comparar el size del set y la length de arr .

Obtendrá una longitud diferente si se repite algún elemento de lo contrario

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

Si desea utilizar una matriz anidada, puede aplanarla antes de enviar arguments a la función getResult como:

 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 Report

0

La forma más sencilla sería recorrer la matriz y verificar si el primer índice del elemento es el mismo que el índice actual como este:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!