Home > Mobile >  Find duplicate names within an array of different files
Find duplicate names within an array of different files

Time:10-04

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

CodePudding user response:

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

CodePudding user response:

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

  • Related