Skip to content

Instantly share code, notes, and snippets.

@mathcodes
Last active May 22, 2022 05:27
Show Gist options
  • Save mathcodes/1751ae4c14f55834c6507512121cef03 to your computer and use it in GitHub Desktop.
Save mathcodes/1751ae4c14f55834c6507512121cef03 to your computer and use it in GitHub Desktop.

array.forEach

Write a function that takes an array of numbers and a function as parameters. The function parameter should do something to a numbers (increment, double, decrement, etc) and return the result. Your function should return the array that results from applying the function parameter to each element in the number arrav.

SOLUTION

const map = (array, func) => {
    const newArray = [];
    array.forEach((num) => {
        const output = func(num);
        newArray.push(output);
    });
    return newArray;
}

SOLUTION EXPLAINED:

 const newArray = [];

In this case, I'll use a forEach array function to iterate over each item in the array.

The forEach() method iterates over each item in the array and executes a provided function once for each element.

    array.forEach((num) => {

And then for each number in the array, we want to get the output of calling func and passing in num.

        const output = func(num);

Now push that output into our new array (NOTE: the push method adds one or more elements to the end of an array and returns the new length of the array.

        newArray.push(output);
    });

Print result & return a the newArray:

    console.log(newArray);
    return newArray;
}

Call the function with some inputs (arguments passed into the parameters)

map([1,2,8], function(num){return num/2})  

RESULT: [0.5, 1, 4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment