samedi 15 mai 2021

I'm having a problem with my Regex code, and it's affecting the way my entire program runs [duplicate]

I'm trying to code a program that will loop through the elements of an array and check if they match a certain character pattern. The matching elements then get pushed onto a new array and the non-matching elements remain still. However I'm not getting the results I expected.

This is my code:

let firstArray = ["file.mp3", "hello.mp3", "four.mp3", "1234.mp4"];
let regex = /[a-z].mp3$/
let nthArray = [];

function getFiles(arr){
    for (const item of arr){
        if (item == regex){
            nthArray.push(item)
        }
    }
    return nthArray
};


console.log(getFiles(firstArray));

The console displays an empty array:

[];

I then tried to switch the if statement to a more specific statement:

function getFiles(arr){
    for (const item of arr){
        if (arr[item] == regex){
            nthArray.push(arr[item])
        }
    }
    return nthArray
};

I still get an empty array on the console.

Can someone please explain to me where I went wrong ? Thanks in advance !

Aucun commentaire:

Enregistrer un commentaire