Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Find duplicate names within an array of different files

A bit of a different use case from the ones I was suggested above. I need to loop through and check each file name within an array of files and push the files that have the same name into a new array so that I can upload them later separately.

This is my code so far, and surely I have a problem with my conditional checking, can somebody see what I am doing wrong?

filesForStorage = [
{id: 12323, name: 'name', ...},
{id: 3123, name: 'abc', ...},
{id: 3213, name: 'name', ...},
...
]

    filesForStorage.map((image, index) => {
          for (let i = 0; i < filesForStorage.length; i++) {
            for (let j = 0; j < filesForStorage.length; j++) {
              if (
                filesForStorage[i].name.split(".", 1) ===.   //.split('.', 1) is to not keep in consideration the file extension
                filesForStorage[j].name.split(".", 1)
              ) {
                console.log(
                  "----FILES HAVE THE SAME NAME " +
                    filesForStorage[i] +
                    " " +
                    filesForStorage[j]
                );
              }
            }
          }
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Using map without returning anything makes it near on pointless. You could use forEach but that is equally pointless when you're using a double loop within - it means you would be looping once in the foreach (or map in your case) and then twice more within making for eye-wateringly bad performance.

What you're really trying to do is group your items by name and then pick any group with more than 1 element

const filesForStorage = [
{id: 12323, name: 'name'},
{id: 3123, name: 'abc'},
{id: 3213, name: 'name'}
]

const grouped = Object.values(
  filesForStorage.reduce( (a,i) => {
    a[i.name] = a[i.name] || [];
    a[i.name].push(i);
    return a;
  },{})
);

console.log(grouped.filter(x => x.length>1).flat());

about 4 years ago · Juan Pablo Isaza Denunciar

0

JavaScript has several functions which perform "hidden" iteration.

  • Object.values will iterate through an object of key-value pairs and collect all values in an array
  • Array.prototype.reduce will iterate through an array and perform a computation for each element and finally return a single value
  • Array.prototype.filter will iterate through an array and collect all elements that return true for a specified test
  • Array.prototype.flat will iterate through an array, concatenating each element to the next, to create a new flattened array

All of these methods are wasteful as you can compute a collection of duplicates using a single pass over the input array. Furthermore, array methods offer O(n) performance at best, compared to O(1) performance of Set or Map, making the choice of arrays for this kind of computation eye-wateringly bad -

function* duplicates (files) {
  const seen = new Set()
  for (const f of files) {
    if (seen.has(f.name))
      yield f
    else
      seen.add(f.name, f)
  }
}

const filesForStorage = [
  {id: 12323, name: 'foo'},
  {id: 3123, name: 'abc'},
  {id: 3213, name: 'foo'},
  {id: 4432, name: 'bar'},
  {id: 5213, name: 'qux'},
  {id: 5512, name: 'bar'},
]

for (const d of duplicates(filesForStorage))
  console.log("duplicate name found", d)

duplicate name found {
  "id": 3213,
  "name": "foo"
}
duplicate name found {
  "id": 5512,
  "name": "bar"
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

A nested loop can be very expensive on performance, especially if your array will have a lot of values. Something like this would be much better.

filesForStorage = [
  { id: 12323, name: 'name' },
  { id: 3123, name: 'abc' },
  { id: 3213, name: 'name' },
  { id: 3123, name: 'abc' },
  { id: 3213, name: 'name' },
  { id: 3123, name: 'random' },
  { id: 3213, name: 'nothing' },
]

function sameName() {
  let checkerObj = {};
  let newArray = [];

  filesForStorage.forEach(file => {
   checkerObj[file.name] = (checkerObj[file.name] || 0) + 1;
  });

  Object.entries(checkerObj).forEach(([key, value]) => {
    if (value > 1) {
      newArray.push(key);
    }
  });

  console.log(newArray);

}

sameName();

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda