Home > Software design >  I need a good way to classify files names in each categories from an array in javascript, but when n
I need a good way to classify files names in each categories from an array in javascript, but when n

Time:11-09

Basically, I have two arrays, one is the types of the files and the other is the actually files names, so, I need to verify each of the file name's and search for an specific string, for then, group up, but has some rules, like, the group has to be in order name ASC and the general has to have either the ones that doesn't match with an type and the ones with the type in it, for the new versions files. (I need to Do this with pure Javascript) Examples:

types: ["general","picture","document","annotation"]
files: [
         {name:"-t_picture_t-my_vacation.jpg"},
         {name:"-t_document_t-my_curriculum.pdf"},
         {name:"my_favorite_music.mp3"},
         {name:"my_dance_video.mp4"},
         {name:"-t_annotation_t-dont_forget.txt"},
       ]

The results expected are something like:

[
 {name:"my_dance_video.mp4"},
 {name:"my_favorite_music.mp3"},
 {name:"-t_picture_t-my_vacation.jpg"},
 {name:"-t_document_t-my_curriculum.pdf"},
 {name:"-t_annotation_t-dont_forget.txt"},
]

Any questions about, just send a message.

CodePudding user response:

Well... a simple algorithm will be something like this

const types = ["picture","document","annotation", "general"]
const files = [
         {name:"-t_picture_t-my_vacation.jpg"},
         {name:"-t_document_t-my_curriculum.pdf"},
         {name:"my_favorite_music.mp3"},
         {name:"my_dance_video.mp4"},
         {name:"-t_annotation_t-dont_forget.txt"},
       ]
       
const result = []
const matches = {}

for (const file of files) {
    for (const type of types) {
        if (file.name.includes(type)) {
          result.push(file)
          matches[file.name] = true
        } else if (type == 'general' && !matches[file.name]) {
            result.unshift(file)
        }
    }
}

console.log(result)

The downside is that we need to wait with general category till the end because only when we complete sorting we can add the rest of items without duplication

Hope that helps for you to kick-start your solution. Enjoy

  • Related