exercice array

Pour toutes les discussions javascript, jQuery et autres frameworks
Répondre
NonOui
Messages : 1
Enregistré le : 30 mars 2022, 14:44

exercice array

Message par NonOui » 30 mars 2022, 14:57

Bonjour,

Je suis étudiant et j'aurais besoin d'aide pour comprendre pourquoi mon code ne marche que partiellement.



Voici l'énoncé:

Mutations
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments ["hello", "hey"] should return false because the string hello does not contain a y.

Lastly, ["Alien", "line"], should return true because all of the letters in line are present in Alien.



Et voici ce que j'ai fait:

function mutation(arr) {

let arrDe1 = arr[0].toLowerCase().split("")
let arrDe2 = arr[1].toLowerCase().split("")
let newArray = []


for(let i = 0; i < arrDe1.length; i++){
for(let j = 0; j < arrDe2.length; j++){


if(arrDe1 === arrDe2[j]){
newArray.push(arrDe2)
}
}
}

if(newArray.length == arrDe2.length){
return true
}

else{
return false
}

}

Malheureusement le code ne marche pas pour: mutation(["hello", "Hello"]) alors que j'ai bien utilisé toLowerCase() pour tout mettre en minuscules pourtant :(

Merci d'avance

Avatar du membre
webmaster
Administrateur du site
Messages : 563
Enregistré le : 28 févr. 2017, 15:19

Re: exercice array

Message par webmaster » 31 mars 2022, 14:01

Bonjour,

Il manquait des indices sur les tableaux. J'ai corrigé comme ceci :

Code : Tout sélectionner

<script>
function mutation(arr) {
    let arrDe1 = arr[0].toLowerCase().split("")
    let arrDe2 = arr[1].toLowerCase().split("")
    let newArray = []
    console.log(arrDe1)
    console.log(arrDe2)

    for(let i = 0; i < arrDe1.length; i++){
        for(let j = 0; j < arrDe2.length; j++){
            if(arrDe1[i] === arrDe2[j]){
                newArray.push(arrDe2[j])
            }
        }
    }
    console.log(newArray)
    if(newArray.length == arrDe2.length){
        return true
    } else{
        return false
    }
}

console.log(mutation( ["Alien", "line"]))

</script>
TJS : 25 ans et mon livre Tout JavaScript chez Dunod
https://www.toutjavascript.com/livre/index.php

Répondre