1 December 2024

Lesson 7 JavaScript Array Methods Lesson Notes

forEach

Description: Executes a provided function once for each array element. Parameters:

  1. element (required) - The current element being processed.
  2. index (optional) - The index of the current element.
  3. array (optional) - The array forEach was called on.

Example Usage:

const arr = [1, 2, 3];
arr.forEach((item, index, array) => {
    console.log(`Element: ${item}, Index: ${index}, Array: ${array}`);
});

map

Description: Creates a new array populated with the results of calling a provided function on every element in the calling array. Parameters:

  1. element (required) - The current element being processed.
  2. index (optional) - The index of the current element.
  3. array (optional) - The array map was called on.

Example Usage:

const arr = [1, 2, 3];
const squared = arr.map((item, index) => {
    console.log(`Index: ${index}, Value: ${item}`);
    return item * item;
});
console.log(squared);

filter

Description: Creates a new array with all elements that pass the test implemented by the provided function. Parameters:

  1. element (required) - The current element being processed.
  2. index (optional) - The index of the current element.
  3. array (optional) - The array filter was called on.

Example Usage:

const arr = [1, 2, 3, 4];
const evens = arr.filter((item, index) => {
    console.log(`Index: ${index}, Value: ${item}`);
    return item % 2 === 0;
});
console.log(evens);

reduce

Description: Executes a reducer function (that you provide) on each element of the array, resulting in a single output value. Parameters:

  1. accumulator (required) - The accumulated result from the previous callback invocation.
  2. element (required) - The current element being processed.
  3. index (optional) - The index of the current element.
  4. array (optional) - The array reduce was called on.
  5. initialValue (optional) - A value to use as the first argument to the first callback.

Example Usage:

const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, item, index) => {
    console.log(`Accumulator: ${acc}, Current Value: ${item}, Index: ${index}`);
    return acc + item;
}, 0);
console.log(sum);

Notes on Initial Value in reduce:

If an initialValue is provided, the accumulator starts with that value, and the first element of the array is skipped. If no initialValue is provided, the accumulator starts with the first element of the array, and the iteration starts with the second element.


The rest of the lesson examples provided above are still valid and work as intended. These additional explanations provide context about the parameters and functionality of each method.

forEach

  1. Print each number in an array.

    const arr = [1, 2, 3];
    arr.forEach(item => console.log(item));
    // Output: 1 2 3
    
  2. Create an array of words and print their lengths.

    const arr = ['apple', 'banana', 'cherry'];
    arr.forEach(item => console.log(item.length));
    // Output: 5 6 6
    
  3. Print the square of each number in an array.

    const arr = [1, 2, 3];
    arr.forEach(item => console.log(item * item));
    // Output: 1 4 9
    
  4. Print each character of every word in an array of strings.

    const arr = ['hello', 'world'];
    arr.forEach(item => {
        item.split('').forEach(char => console.log(char));
    });
    // Output: h e l l o w o r l d
    
  5. Calculate and print the sum of all numbers in an array.

    const arr = [1, 2, 3];
    let result = 0;
    arr.forEach(item => {
        result += item;
    });
    console.log(result);
    // Output: 6
    

map

  1. Convert an array of numbers to their squares.

    const arr = [1, 2, 3];
    const newArr = arr.map(item => item * item);
    console.log(newArr);
    // Output: [1, 4, 9]
    
  2. Convert all strings in an array to uppercase.

    const arr = ['apple', 'banana', 'cherry'];
    const newArr = arr.map(item => item.toUpperCase());
    console.log(newArr);
    // Output: ['APPLE', 'BANANA', 'CHERRY']
    
  3. Add the string '-done' to every element in an array of tasks.

    const arr = ['task1', 'task2', 'task3'];
    const newArr = arr.map(item => `${item}-done`);
    console.log(newArr);
    // Output: ['task1-done', 'task2-done', 'task3-done']
    
  4. Extract only the first letters from an array of words.

    const arr = ['apple', 'banana', 'cherry'];
    const letters = arr.map(item => item[0]);
    console.log(letters);
    // Output: ['a', 'b', 'c']
    

filter

  1. Filter even numbers from an array.

    const arr = [1, 2, 3, 4, 5, 6];
    const evenArr = arr.filter(item => item % 2 === 0);
    console.log(evenArr);
    // Output: [2, 4, 6]
    
  2. Filter words longer than 5 characters.

    const arr = ['apple', 'banana', 'cherry', 'date'];
    const words = arr.filter(item => item.length > 5);
    console.log(words);
    // Output: ['banana', 'cherry']
    
  3. Filter numbers greater than 20.

    const arr = [10, 15, 20, 25, 30];
    const bigger = arr.filter(item => item > 20);
    console.log(bigger);
    // Output: [25, 30]
    
  4. Filter strings that contain the letter 'a'.

    const arr = ['apple', 'banana', 'cherry', 'date'];
    const letterA = arr.filter(item => item.includes('a'));
    console.log(letterA);
    // Output: ['apple', 'banana', 'date']
    
  5. Filter only unique elements from an array.

    const arr = [1, 2, 2, 3, 4, 4, 5];
    const unique = arr.filter((item, index) => arr.indexOf(item) === index);
    console.log(unique);
    // Output: [1, 2, 3, 4, 5]
    

reduce

  1. Return one string of all names in uppercase.

    const arr = ['alex', 'mike', 'tom'];
    const name = arr.reduce((acc, item) => `${acc} ${item.toUpperCase()}`, '').trim();
    console.log(name);
    // Output: 'ALEX MIKE TOM'
    
  2. Multiply numbers in an array.

    const arr = [1, 2, 3];
    const mult = arr.reduce((acc, item) => acc * item, 1);
    console.log(mult);
    // Output: 6