Unusual Behavior Observed in JavaScript Map Reduce

var t = [-12, 57, 22, 12, -120, -3];

t.map(Math.abs).reduce(function(current, previousResult) {
    return Math.min(current, previousResult);
}); // returns 3

t.map(Math.abs).reduce(Math.min); // returns NaN

I'm puzzled as to why the second variant doesn't produce the expected result. Any insights on this issue would be appreciated.

UPDATE: Just for context, this pertains to Chrome and Firefox's JavaScript engines. For more details on ES5 reduce method, check out http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.21

Answer №1

Math.min is capable of accepting multiple arguments, unlike functions such as parseInt. When using Math.min with reduce, the values like index and array are passed to it.

To demonstrate this concept, we can proxy Math.min by following these steps:

First, we create a proxy for Math.min:

var oldMath = Math.min;
Math.min = function (){
   console.log(arguments)
   return oldMath.apply(Math, arguments);
}

Then we execute the second version:

[-12, 57, 22, 12, -120, -3].reduce(Math.min);

This will output:

[-12, 57, 1, Array[6]]

As the last element in the array is not a number, the result becomes NaN


A similar example from MDN illustrates this point:

["1", "2", "3"].map(parseInt);

While one might expect [1, 2, 3], the actual result would be [1, NaN, NaN]

parseInt typically only uses one argument, but it actually takes two – the second being the radix. When used with Array.prototype.map, parseInt receives 3 arguments: the element, the index, and the array. While the third argument is disregarded, the second could lead to confusion due to how parseInt function interprets it.

Answer №2

reduce's callback function receives four parameters: previousValue, currentValue, index, and array. Since Math.min is a variadic function, the code:

t.map(Math.abs).reduce(Math.min); // returns NaN

is essentially the same as:

t.map(Math.abs).reduce(function(current, previousResult, index, array) {
  return Math.min(current, previousResult, index, array);
});

This results in NaN because the last parameter, array, is not a number.

To solve this issue, you can use a higher-order function like the following:

function binary (fn) {
  return function (a, b) {
     return fn.call(this, a, b);
  }
}

Then, you can modify your code to:

t.map(Math.abs).reduce(binary(Math.min));

and it should work correctly.

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

JavaScript: Retrieving the names of children within a <div> element

Within my structure setup, there is a tower div with inner elements like this: <div class="tower"> <div class="E0">abc</div> <div class="GU">123</di </div> The challenge I am facing is that I need to access the in ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

"Enhance input functionality by updating the value of the text input or resizing the textbox

I've been facing a challenge with updating the value of my input type=text or textbox control text value using jQuery $(window).resize(function(){});. I am aware that the event is triggered because an alert pops up when I resize the browser. Additiona ...

Load data from a MySQL Database into a DataTable

I am currently in the process of developing a CRUD application. With a large dataset stored in a MySQL database, my intention is to utilize a JQuery DataTable instead of manually creating a table. However, the issue I am facing is that while the table appe ...

Is the treatment of __proto__ different in the fetch API compared to manual assignment?

When using fetch to retrieve a payload containing a __proto__, it seems that the Object prototype is not affected in the same way as when directly assigning to an object. This behavior is beneficial as it ensures that the Object prototype remains unaffect ...

What is the most effective way to add HTML from a dynamically loaded document using AJAX?

I am attempting to attach the information from a .html file to the body of my main webpage. Essentially, I am striving to create a reusable section of html that can be loaded into any page with a basic JavaScript function. Below is the content of my navig ...

Determining which data is retrieved from a database based on a specific field using Sequelize and MySQL

I'm looking to retrieve the most recent records from a database, organized by category. My goal is to fetch 20 records, with 5 of the latest posts in each category. I want to ensure that the result consists of 20 total records, evenly distributed amon ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

How to execute a function in a child process using node.js?

In my node.js application, I am receiving a file through a web request and need to perform a time-consuming conversion process on it. To prevent this task from affecting the main thread's performance, I currently have it triggered by a setTimeout() ca ...

Hiding elements in HTML with React when data is null

Is there a way to hide elements using classes like "d-none" when the data is null in React? <span className="product__tag">{prod.tag1}</span> <span className="product__tag">{prod.tag2}</span> <span classN ...

I am facing difficulties with invoking the popOpen() function within my parameters in JS, HTML, and CSS

I'm currently facing an issue with my code. I am attempting to invoke my openPop() function with the input parameter 'pop' within some of my sensor code, but no pop-up is appearing even though I believe I am calling the popup correctly. If a ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

Why is the second row of inputs not displaying in Vue.js?

I am currently developing a Single Page Application (SPA) that includes options with variants, similar to the image shown below: [1]: https://i.sstatic.net/82I5U.png However, I have encountered an issue where the second row of inputs for variants is not b ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

Challenges with creating a contact form using bootstrap modal

I'm facing an issue with a bootstrap modal contact form. It works fine on all browsers except for iPad/Safari. Can anyone help me figure out what's wrong? On iPad, the modal is positioned to the right and down the page instead of in the cente ...

The type '{ children: Element[]; }' does not include the properties 'location' and 'navigator' that are present in the 'RouterProps' type

Struggling to implement React Router V6 with TypeScript, encountering a type error when including Routes within the `<Router />` component. The error message indicates that the children property passed to the Router is of an incorrect type, despite u ...

Retrieving online content and updating it upon reestablishing internet connection

Currently, I am in the process of developing an app that will feature a substantial amount of web content. My plan is to use Phone Gap build for its release; however, I intend to host all the content online and link to it from within the app. I have been c ...

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

The issue with the max-height transition not functioning properly arises when there are dynamic changes to the max-height

document.querySelectorAll('.sidebarCategory').forEach(el =>{ el.addEventListener('click', e =>{ let sub = el.nextElementSibling if(sub.style.maxHeight){ el.classList.remove('opened&apos ...