Leveraging array.prototype.map along with an average function

Despite thoroughly reading the documentation on the map method, I am still unable to make this code work. My objective is to use map to calculate the average of each pair of numbers in an array. Can someone please help me understand what's going wrong?

function getAverage(num1,num2){return Math.ceil((num1+num2)/2)}; 

function calculateAverages(input){ var result = input.map(getAverage(num1,num2)); return result; } 

calculateAverages([1,2,3,4]) // error num1 is not defined
// expected [2,4]

Answer №1

map applies a function to each element within a list or array, essentially "mapping" the function over all the items.

[1, 2, 3].map(function (number) { return number + 1; });
// -> [2, 3, 4]

Therefore, you must first ensure that your "input" array consists of pairs of items, like so:

var numberPairs = [[1, 2], [3, 4]]

Up until this point, you only have individual numbers and not actual pairs.

Once converted, you can utilize map in the following manner:

numberPairs.map(function (pair) {
  return Math.ceil((pair[0] + pair[1]) / 2);
});

This will yield:

[2, 4]

as the final outcome.

Answer №2

Calculating the average using a map is not possible. When you use a map, a function is passed to each element and an array with the same shape is returned. If you want to obtain a value from an array and calculate the average, you should utilize the reduce method.

// Function that adds two numbers
const adder = (a,b) => a + b;
// Reduces the array by adding all numbers and then divides by the length of the array
const getAverage = (arr) => arr.reduce(adder)/arr.length;

// Outputs 2.5 as the result for averaging [1,2,3,4]
console.log(getAverage([1,2,3,4])) 

Answer №3

If you want to calculate the average of every n values in an array, try using the reduce() method instead of map():

const total = arr => arr.reduce((acc, value) => acc + value, 0);
const computeAverage = n => (averages, val, index, arr) => index % n === 0
  ? [...averages, Math.ceil(total(arr.slice(index, index + n)) / n)]
  : averages

const result = [1, 2, 3, 4].reduce(computeAverage(2), [])
console.log(result)

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

In nodejs, the exported object is returning an undefined value

Within my app.js file, I have exported an object with properties and values. However, when including this file in the route, I am encountering issues where the value is returned as undefined. Interestingly, if I omit the argument "users" in the createUser ...

Experiencing unexpected behavior when attempting to dynamically add a tab item

<div class="page-content"> <div class="content-block"> <div id="tab-holder" class="buttons-row"> <a href="#tab1" class="tab-link active button">Tab 1</a> <a href="#tab2" class="tab-link button">Tab 2< ...

Is there a way to transfer a set of data into another collection within Angularfire, Angular, or Firestore and designate it as a sub

I currently manage two unique collections: Collection 1 consists of various modules, While Collection 2 includes profiles nested within modules as a sub-collection. My goal is to transfer all documents from Collection 1 to Collection 2 in a one-time ope ...

Get access to a JSON key using forward slashes in Node.js

I'm facing an issue with accessing a property in an object that contains forward slashes. Specifically, I need to access the child key pattern. Unfortunately, my attempts so far have been unsuccessful. Please provide a solution to access the pattern p ...

Utilizing the Ternary Operator within ReactJs Card Headers

Is it possible to include a ternary operator in the title of CardHeader using ReactJS? I am able to include the first name but encountering issues with including the last name as well. <CardHeader title={(firstName ? firstName : "") + " " + (lastName ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

Troubles with setting up slash commands in discord.js v13

I am encountering an issue while trying to deploy a slash command. The error message DiscordAPIError[50035] is displayed, stating "Invalid Form Body guild_id[NUMBER_TYPE_COERCE]: Value \"undefined\" is not snowflake." const path = require('n ...

Is it Possible to Insert Function from a For... in Loop?

Question: How is a function being attached to a variable's memory space without being explicitly assigned? Situation: I have developed a script to eliminate duplicate objects by comparing the values of object keys. However, after initializing the che ...

changing the variable to implement a new function in React

I'm encountering an issue with updating the marker for the Maps component using the Local_Value. Despite utilizing the getMap() function to update the Local_Value, it fails to reflect the changes globally and update the marker. The getMap() function ...

What is the best way to set a default parameter value for an npm script command?

In my package.json file, I have the following: scripts: { "echo": "echo ${1-'/*'}" } When I execute npm run echo, it outputs /*, which is desired as it represents all paths from the root. However, upon running npm run echo /salad, the outpu ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

Disappear the form after the user clicks submit

I'm developing a PHP application and I need a way for the form to disappear or hide once the user clicks submit. The form should not reappear for the same user. form.php <?php session_start(); include('config.php'); if( ...

The firing of jQuery UI dropover is not consistent

On my page, I have two droppable DIVs. One of them (#droppable2) is hidden at first and only appears when I hover the draggable item over the first DIV #droppable (using the dropover event). You can see an example here: http://codepen.io/anon/pen/AdLJr &l ...

Dealing with varied indices in two distinct arrays

Suppose I have two arrays: y=[0,1,1] and x=[0,0,4,10,5]. Additionally, there is an Index-array containing the indices of the non-zero entries from x: I_x=[2,3,4]. My ideal scenario would be to have something like y[2]=0, y[3]=1, y[4]=1. Is there a way to ...

Add a directive on the fly, establish a connection, and display it dynamically

Within my markup, I have a tag element called popup-window which is handled by a specific directive. If I wish to incorporate multiple similar widgets that can be displayed or hidden in various locations, I currently need to include all these elements dire ...

PHP dropdown menu triggering a secondary dropdown menu to filter and display search results

Yes, I may be a PHP beginner but I have successfully cobbled together some PHP code that can query specific data and generate a dropdown menu. Now, I want to customize this code to create another dropdown menu. However, this new dropdown should display re ...

Encountering issues with displaying images in React Next.js when utilizing dangerouslySetInnerHtml

While working on creating a simple WYSIWYG editor in nextjs, I encountered an issue with displaying uploaded images on the screen. When generating a blob URL for the image and using it as the src attribute of the image tag, it worked fine unless dangerousl ...

Is it possible to vectorize the calculation of the minimum and maximum values in slices

Let's say I have a NumPy array filled with random integers. arr = np.random.randint(0, 1000, 1000) In addition to this, I also have two arrays named lower and upper. These arrays determine the lower and upper bounds for specific slices of arr. Thes ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

How can Angular incorporate JSON array values into the current scope?

I am currently working on pushing JSON data into the scope to add to a list without reloading the page. I am using the Ionic framework and infinite scroll feature. Can someone please point out what I am doing wrong and help me figure out how to append new ...