Array methods · Méthodes de tableau
Array methods
.map(fn)makes a new array by transforming each item..filter(fn)makes a new array of only the items wherefnreturnstrue..forEach(fn)runsfnfor each item, making no new array.
Méthodes de tableau
.map(fn)crée un nouveau tableau en transformant chaque élément..filter(fn)crée un nouveau tableau contenant uniquement les éléments oùfnretournetrue..forEach(fn)exécutefnpour chaque élément, sans créer de nouveau tableau.
let nums = [1, 2, 3];
let doubled = nums.map((n) => n * 2);
console.log(doubled); // → [2,4,6]
Filtering keeps some items
.filterkeeps each item for which the test returnstrue.
Filtrer garde certains éléments
.filtergarde chaque élément pour lequel le test retournetrue.
let nums = [3, 7, 2, 9];
let big = nums.filter((n) => n > 4);
console.log(big); // → [7,9]
Watch out
.mapand.filterreturn a new array — the original is untouched.- You hand each one an arrow function that says what to do with one item.
Attention
.mapet.filterretournent un nouveau tableau — l'original reste inchangé.- Vous passez chacun une fonction fléchée qui dit quoi faire avec un élément.
Common mistakes
mapandfilterreturn a NEW array — they do not change the original.forEachjust loops and returns nothing.
Erreurs courantes
mapetfilterretournent un NOUVEAU tableau — ils ne changent pas l'original.forEachfait juste une boucle et retourne rien.
Now you try
- Use
.map,.filteror.forEach. - Press Check answer to test it.
À vous maintenant
- Utilisez
.map,.filterou.forEach. - Appuyez sur Vérifier la réponse pour tester.
Use .map to double every number in [1, 2, 3] and store the new array in result (it should be [2, 4, 6]). · Utilisez .map pour doubler chaque nombre dans [1, 2, 3] et stockez le nouveau tableau dans result (il devrait être [2, 4, 6]).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Use .filter to keep only the numbers greater than 4 from [3, 7, 2, 9, 1], in a variable big (it should be [7, 9]). · Utilisez .filter pour ne garder que les nombres supérieurs à 4 de [3, 7, 2, 9, 1], dans une variable big (il devrait être [7, 9]).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Use .forEach to add every number in [4, 8, 15] to · à total (it should end up 27). · Utilisez .forEach pour additionner chaque nombre de [4, 8, 15] à total (il devrait finir par être 27).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.