Advertisement
makispaiktis

Iterators

Oct 18th, 2024 (edited)
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 1. For Each
  2. const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];
  3. artists.forEach(artist => {
  4.   console.log(artist + ' is one of my favorite artists.');
  5. });
  6.  
  7. // 2. Map
  8. const numbers = [1, 2, 3, 4, 5];
  9. const squareNumbers = numbers.map(number => number * number);
  10. console.log(squareNumbers);
  11.  
  12. // 3. Filter
  13. const things = ['desk', 'chair', 5, 'backpack', 3.14, 100];
  14. const onlyNumbers = things.filter(thing => typeof thing === 'number');
  15. console.log(onlyNumbers);
  16.  
  17. // 4. Reduce with 2 parameters: a callback function and a value for accumulator initialization
  18. const newNumbers = [1, 3, 5, 7];
  19. const newSum = newNumbers.reduce(((accumulator, currentValue) => {
  20.     console.log('The value of accumulator: ', accumulator);
  21.     console.log('The value of currentValue: ', currentValue);
  22.     return accumulator + currentValue}), 10);
  23. console.log(newSum);
  24.  
  25. // 5. Some
  26. const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
  27. console.log(words.some(word => word.length < 6));
  28.  
  29. // 6. Every
  30. const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
  31. console.log(interestingWords.every(word => word.length > 5));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement