Use the forEach method to replicate the functionality of the map function

Attempting to replicate the functionality of array.map() using forEach().

var map = function () {
  var empMap = [];
  numbers.forEach(function (number) {
    empMap.push(number);
    console.log('empMap', empMap);
  });
  return(empMap);
}

var numbers = [1, 2, 3];
//need to implement this part

var doubles = map(numbers, function (number) {
  return number * 2;
});
console.log(doubles); // [2, 4, 6]

The scenario involves an array named numbers with specific values and a custom map function designed to traverse through the array, storing the values in an empty array called empMap.

Subsequently, the map function is invoked to multiply each value by 2 and display the result.

The expected output for doubles is [2, 4, 6], however, the actual outcome is [1, 2, 3]. The cause of this discrepancy is currently unknown.

A link to see the implementation on CodePen: [codepen]1

Answer №1

The array and callback must be passed as arguments, followed by actually utilizing the callback function.

function mapArray(array, callback) {
  var mappedArray = [];

  array.forEach(function (element) {
    mappedArray.push(callback(element));
  });

  return(mappedArray);
}

var numbers = [1, 2, 3];

var doubles = mapArray(numbers, function (element) {
  return element * 2;
});

console.log(doubles); // [2, 4, 6]

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

Undefined response received when parsing JSON data

Hey there, I'm currently working on an ajax request that submits a form and sends an email. If the email is successfully submitted, I encode a PHP array that has a structure like this: $success = array("state" => "Email Sent"); My issue arises wh ...

Enhancing arrays within arrays using MongoDB

Encountering difficulties in accessing a nested array within an array in a mongodb document. The first array "groups" can be accessed without any problems using the query: db.orgs.update({_id: org_id, "groups._id": group_id} , {$set: {"groups.$.name": "ne ...

Is there a way to adjust the dimensions of Google charts within a Bootstrap tab for a more customized appearance?

I've been working on a page that features tab navigation using Twitter Bootstrap and I want to include Google charts within each tab's content. However, I've encountered an issue where the charts are appearing in different sizes despite spec ...

Issue "Unable to access property 'fname' because it is undefined" within React state

Whenever I use console.log with fullname, it displays fname and lname. However, when trying to access them as fullname.fname or fullname.lname in the component, an error is thrown saying "Cannot read property 'fname' of undefined". I have initia ...

Is there a way to verify Page.Validate() using client-side JavaScript in ASP.Net?

Is there a client-side function in JavaScript that can perform page validation similar to the server-side method Page.Validate()? ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

Switching case in jQuery for JSON information retrievalWhen retrieving JSON information using jQuery,

As a newbie in the world of jQuery (and javascript), I kindly ask for mercy! :) I am currently working on retrieving information from a JSON database. I have set up a search box and found a solution for fetching the data successfully when entering the exa ...

Encountered an issue when trying to adjust the state in my REACT application

While working on a small project to enhance my knowledge of React, I encountered the following error: " Line 19.5: 'state' is not defined no-undef ". I'm puzzled about what could be causing this... Interestingly, I have used a simi ...

Can the appearance of the model be adjusted when using the GLTF or GLB format in Three.js?

Initially, I encountered an issue where my model appeared completely black. Although some sources suggested it was due to lighting, adjusting the light did not improve the model. Ultimately, I discovered that the problem lied within the model itself, and I ...

Trouble with radio button selection using onclick event in Bootstrap

I've been attempting to implement an onclick event with radio buttons in Bootstrap, but unfortunately the event isn't triggering. Here's the code I'm using: <input type="checkbox" onclick="alert('Scenery!')"/> However, ...

What is the best method for creating table column text within a Bootstrap Modal through JSON data?

I am currently working on creating a table by using key value pairs from a JSON object. The keys will represent column-1 and the values will correspond to column-2. The desired output can be viewed at this link. I am wondering if there is a standard method ...

Is it possible to embed PHP code within HTML?

Can you identify any issues in the code below? Everything works fine when I remove the PHP variable $var, but I actually need to insert a value of 5000 into it. echo '<div id="img1" style="position:absolute;left:81px;top:127px;width:12px;height:12 ...

When there is only a single div content in Ant Design Vue, Carousel arrows have been observed to disappear

I have integrated the Ant Design Vue Carousel into my Instagram Story Clone project to showcase dynamically generated backend data. However, I've encountered an issue where the arrows and dots disappear when there is only one item in the carousel. Y ...

Achieving the new value without retrieving the old value in a jQuery on('save') event

I am currently utilizing X-editable and attempting to retrieve the value of an element when a user changes it. However, I am encountering difficulties as I am only getting the previous value instead of the changed value. For example, if the original value ...

What is the best way to select specific elements within a table cell with vuejs?

I am facing an issue with a dynamically rendered table where each cell contains data in a readonly input box. The first cell has an edit button, and when clicked, the input boxes should become editable for user input. The edit button should then be hidden, ...

Storing Code into mongoDB with the Help of CasperJS

What is the best way to save data scraped using casperjs into MongoDB? My casperjs script scrapes information from millions of websites and saves each site's content in its own folder. However, I have come to realize that it would be more efficient to ...

Issue: ENOENT - The file or directory does not exist. uv_chdir encountered an error when attempting to create a directory and navigate into it

I am facing a challenge while developing a small application that installs files and modules in a new folder. The error I keep encountering is: { Error: ENOENT: no such file or directory, uv_chdir at process.chdir (/home/aboardwithabag/LaunchProject/n ...

What is the best method for finding the value of an element?

Here is the snippet of code that I'm working with: if($('span').text().indexOf("t")){ console.log($('span').text()); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <sp ...

The conversion to ObjectID did not succeed due to an issue on the front end

I have encountered an issue while trying to send a post request to create a task within a list using an API provided to me. This error occurs when I attempt to make the request in postman. Below is the schema of the post request body required by the API, ...

Populate Dialog Form with Parent Data in React using Typescript

Incorporating Reactjs and Typescript, I am facing an issue with a parent component that retrieves data from an API and then uses it to trigger the opening of a Material-UI Dialog containing an editable form. The problem lies in prepopulating the dialog wit ...