Sending Parameters into collection of inline functions

Task Instructions: Your task is to create a function called multiMap that takes in two arrays as parameters: one array of values and one array of callbacks. The multiMap function should return an object where the keys correspond to the elements in the values array. Each key's value should be an array containing the outputs from each callback function, with the input being the key itself.

My Approach:


let obj = {};
for(let i = 0; i < arrVals.length; i++) {
    obj[arrVals[i]] = [arrCallbacks.apply(null, arrVals[i])];
}
return obj;
}

console.log(multiMap(['catfood', 'glue', 'beer'], [function(str) { return str.toUpperCase(); }, function(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }, function(str) { return str + str; }]));
// expected output: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }

Reflections: While my object keys are correctly set, I encountered difficulty passing the values from the arrVals parameter into the anonymous functions listed in the arrCallbacks parameter. Even after attempting to set my key value to [arrCallbacks[i](arrVals[i])], only the first element was populated in the array. I need all three values from the functions to be passed into the value of each key. I'll have to troubleshoot this further...

Answer №1

Upon examining your code, it appears that you are using the apply method on the callbacks array instead of on each individual callback. This could be the reason why it is not functioning properly.

Based on my observation:

function multiMap(values, callbacks) {
  let result = {}
  // Loop through the values
  for (const value of values) {
    // Create an array with the output of each callback
    result[value] = callbacks.map((callback) => callback(value));
    // Alternative approach using apply
    // result[value] = callbacks.map((callback) => callback.apply(null, value));
  }
  return result
}
console.log(multiMap(['catfood', 'glue', 'beer'], [function(str) { return str.toUpperCase(); }, function(str) { return str[0].toUpperCase() + str.slice(1).toLowerCase(); }, function(str) { return str + str; }]));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the onreadystatechange method is the preferred way to activate a XMLHttpRequest, as I am unable to trigger it using other methods

I have a table in my HTML that contains names, and I want to implement a feature where clicking on a name will trigger an 'Alert' popup with additional details about the person. To achieve this, I am planning to use XMLHttpRequest to send the nam ...

handlebars and expressjs having trouble displaying the data

Hey there! I'm currently working on an application with express.js and handlebars. I've set up a get method to retrieve employee data when the user enters http://localhost:3000/id/2 in their browser. The id should be 2, and it's supposed to ...

Easily transforming data between JSON and CSV formats in JavaScript using user-defined headers

Can someone provide guidance on creating import/export functionality for CSV format without using external libraries? It would be a huge help! I have a CSV string labeled as "A": "First Name,Last Name,Phone Number\r\nJohn,Doe,0102030405&bso ...

Creating a Dynamic Login Panel Using HTML, CSS, and Jquery

Designing a dynamic sliding login panel utilizing Html, CSS, and jquery alongside various plugins. Check it out here: http://24.125.42.135/ When activated, the bar smoothly pushes down the content (click on the login option at the top right corner). This ...

Attempting to populate a PHP array

After gathering the names and number of players from a previous page, my goal is to store them in an array. Here is the code I have written: <?php $numberOfPlayers = $_POST['numberOfPlayers']; $counter = 1; $playerName = array(); while($cou ...

The integration of a webview within an Ionic application

I have developed a mobile app using the Ionic framework and now I am trying to incorporate a webview using Chrome browser instead of the default browser. Initially, I used the cordova-plugin-inappbrowser plugin but found it to be unstable. I then tried t ...

The array is yielding a key instead of a value

In my array, I have values for each day of the week from Monday to Sunday. My goal is to retrieve the value corresponding to the current day and use it in JavaScript. Below is an example of how the array is structured: Array( [Wednesday] => Array ...

An inquiry regarding props in JavaScript with ReactJS

Check out the following code snippet from App.js: import React from 'react' import Member from './Member' function App () { const members = [ { name: 'Andy', age: 22 }, { name: 'Bruce', age: 33 }, { n ...

The fetch API does not retain PHP session variables when fetching data

After setting session variables in one php file, I am attempting to access those values in another php file. session_start(); $_SESSION['user'] = $row['user']; $_SESSION['role'] = $row['role']; However, when ...

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

Accessing the values of a three-dimensional array with the dereferencing method

#include "stdio.h" int main(){ int A[2][3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; printf("A: %p\n", A); printf("*(0x0061FEC8): %d\n", *((int *)(0x0061FEC8))); printf("*D: %p&b ...

Looking for the nearest element in AngularJS

I am attempting to create a slide toggle effect on the closest .contactDetails element when clicking on a. However, my current code is not producing the desired result. <ul> <li ng-repeat="detail in details"> <div> ...

What is the best way to toggle the visibility of a div's border in my current situation?

Let's talk about a div element: <div id="fruit-part"> <input type="radio" name="fruits" value="apple">Apple <input type="radio" name="fruits" value="orange">Orange </div> Here is the CSS that defines the border co ...

The process of filtering a model stops at the third character and results in an empty output

Whenever I input a value into the 'temp_dollars' model and use a watch property to filter it, the input only retains the first 3 characters and resets. For instance: When I type 123, The model value remains as 123. But wh ...

Storing data values from a specific object key into an array in Vue: Step-by-step guide

Just dipping my toes into the world of Vue framework here. I managed to create a selectable table that stores data in an object. I want this function to run in the background, so I figured it should be in the computed section. The object structure is as fo ...

Disable button not necessary when validating checkboxes

I'm working on a simple function that involves 3 checkboxes. The goal is to disable the button if all checkboxes are unchecked, and enable it only when all three checkboxes are checked. function checkAll() { var checkbox1 = document.getElem ...

Break up the Array column within a PySpark dataframe

I have a DataFrame structured as follows: col1 ----------------- [a1_b1_c1, a2_b2_c2, a3_b3_c3] [aa1_bb1_cc1, aa2_bb2_cc2, aa3_bb3] [aaa2_bbb2_ccc1, aaa2_bbb2_cc2, aaa3_bbb3] My goal is to split the elements and create a new DataFrame with the follow ...

Changing the URL for the onClick event of a button in Laravel through AJAX

I am working on a basic form that includes a "Submit" button and an extra "Add" button in a blade template. When the form is submitted, there is an ajax call to a controller for validation of the provided value. Depending on the response from the controlle ...

Revisiting unions with TypeGraphQL

Here is the code snippet I'm working with: const retrieveUsers = ({ Model, options, }) => Model.find(options).catch((e) => { throw e; }); @ObjectType({ description: "User model" }) @Entity() export class UserModel extends BaseEnti ...

Exploring the globe using Three.js and WebGL: Visualizing countries and their colors on a sphere

I was able to create a globe similar to this example. However, I am facing an issue when trying to retrieve the countries visible in the scene in Three.js when the globe is stationary. I can successfully retrieve the color code of a specific country when h ...