JS Assignment 16: Using Callbacks in Array Methods
maximussallam (5)

function exerciseOne(names){
// Exercise One: In this exercise you will be given and array called names.
// Using the forEach method and a callback as it's only argument, console log
// each of the names.
}

function exerciseTwo(cents){
// Exercise Two: In this exercise you will be given an array called 'cents'
// This array is a list of prices, but everything is in cents instead of dollars.
// Using the map method, divide every value by 100 and save it as a new array 'dollars'

// Please write your answer in the lines above.
return dollars;
}

This is what I have:

function exerciseOne(names){
// Exercise One: In this exercise you will be given and array called names.
// Using the forEach method and a callback as it's only argument, console log
// each of the names.
console.log(names);
}

function eachMethod(array, cb){
for(let i = 0; i < array.length; i++){
cb(array[i]);
}
}
console.log(names.forEach(exerciseOne));

function exerciseTwo(cents){
// Exercise Two: In this exercise you will be given an array called 'cents'
// This array is a list of prices, but everything is in cents instead of dollars.
// Using the map method, divide every value by 100 and save it as a new array 'dollars'
return cents / 100;
}
dollars.map(exerciseTwo);
// Please write your answer in the lines above.
return dollars;
}

What did I do wrong?

You are viewing a single comment. View All
Answered by vedprad1 (835) [earned 5 cycles]
View Answer
malvoliothegood (365)

Study these examples: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
And:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Note that the map example can be written:

var array1 = [1, 4, 9, 16];

// This function doubles the input value and returns it
function doubler(x) {
    return x * 2;
}
// pass the function to map
const map1 = array1.map(doubler);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
CodeDee (1)

@malvoliothegood this helped a lot, but using your example, I am not sure why the following is the following incorrect?:

function exerciseTwo(cents){
// Exercise Two: In this exercise you will be given an array called 'cents'
// This array is a list of prices, but everything is in cents instead of dollars.
// Using the map method, divide every value by 100 and save it as a new array 'dollars'

function dividesbyonehundred (price){
  return price / 100;
}

let answer = cents.map(dividesbyonehundred);

// Please write your answer in the lines above.
  return dollars;
}
CodeDee (1)

@CodeDee Nevermind! I introduced "answer" and the assignment already returned "dollars". The following is an accepted solution:

function exerciseTwo(cents){
function dividesbyonehundred (price){
  return price / 100;
}
let dollars = cents.map(dividesbyonehundred);
  return dollars;
}