Search code examples
javascriptfunctionloopscallbackarguments

JavaScript: Create function that returns an object whose keys match the elements in the array of values using callbacks


My objective is as follows:

Construct a function multiMap that will accept two arrays - an array of values and an array of callbacks. multiMap will return an object whose keys match the elements in the array of values. The corresponding values that are assigned to the keys will be arrays consisting of outputs from the array of callbacks, where the input to each callback is the key.

I tried the code below:

const multiMap = (arrOne, arrTwo) => {

  let newObj = {}; 

  for (let i=0; i<arrOne.length; i++){
    let element = arrOne[i]; 

    console.log(i)

    newObj[element] = arrTwo[i](element); 
  }
  return newObj; 
}



// Uncomment these to check your work!
function uppercaser(str) { return str.toUpperCase(); }
function capitalize(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }
function repeater(str) { return str + str; }

// arrOne
const items = ['catfood', 'glue', 'beer'];
// arrTwo
const functions = [uppercaser, capitalize, repeater];


console.log(multiMap(items, functions));

My code returns: { catfood: 'CATFOOD', glue: 'Glue', beer: 'beerbeer' }

I want it to return: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }, 'Beer', 'beerbeer'] }

What am I doing wrong?

Note: I know I can use modifying functions (i.e. reduce) to do this but I want to figure it out first using for loop.


Solution

  • The problem is that you are looping only over the first array. You have to go through all the functions for each value in the array one.

    const multiMap = (arrOne, arrTwo) => {
    
      let newObj = {}; 
    
      for (let i=0; i<arrOne.length; i++){
        let element = arrOne[i];
        newObj[element] = [];
        for(let j=0;j < arrTwo.length; j++) {
         
        newObj[element].push(arrTwo[j](element)); 
        }
      }
      return newObj; 
    }
    
    
    
    // Uncomment these to check your work!
    function uppercaser(str) { return str.toUpperCase(); }
    function capitalize(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }
    function repeater(str) { return str + str; }
    
    // arrOne
    const items = ['catfood', 'glue', 'beer'];
    // arrTwo
    const functions = [uppercaser, capitalize, repeater];
    
    
    console.log(multiMap(items, functions));