Utilize array.prototype.reduce() with strings

I'm puzzled about how the reduce operation is carried out on a string. Initially, a new Str instance is created with the desired string as a parameter.

Following that, the split method is used to divide the string into an array of strings. A method called reduceIt takes this array and performs a reduce operation which returns the element in the array with the longest length.

Everything works well when dealing with a two-element array. However, if there are more than two elements, it ends up returning NAN.

What causes it to return NAN for arrays with more than two elements?

function Str(text){
   this.text=text.split('\n');
}
Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {
          return Math.max(first.length,last.length);

  });
};

var t=new Str('i am a boy\n she loves cats\n a goat ate my flower garden ');
console.log(t.reduceIt());

Answer №1

When the callback is triggered for the first time, the variable first holds a string value (the initial array element). The function logic is based on both first and last being strings, meaning it only works when the callback is invoked once (if the array contains no more than 2 elements).

On the second invocation, the callback's output becomes a numeric value as a result of the previous call. Trying to access the property length on a number yields undefined, causing Math.max to return NaN.

To determine the length of the longest string in the array, you can use the following code:

Math.max.apply(Math, this.text.map(function (str) { return str.length; }));

Answer №2

Great responses so far! 😊

To resolve your issue, a quick solution is to set an initial value of 0 and then compare the result with the length of the updated string like this:

Str.prototype.adjustLength = function() {
  return this.text.reduce(function(maxSoFar, currentString, index, arr) {

          // Compare current value (maxSoFar) with length of string
          return Math.max(maxSoFar, currentString.length);

  }, 0); // Start with 0 as the initial value
};

Renaming maxSoFar to currentMax and currentString to nextString could improve clarity.

Answer №3

Why does it return NAN when the array has more than two elements?

This occurs because number.length is considered as undefined. To clarify, let's define your function as foo and observe its execution:

  1. foo(0, "i am a boy") results in NaN
  2. foo(NaN, " she loves cats") leads to NaN
  3. foo(NaN, " a goat ate my flower garden ")
    also gives NaN

Thus, the final output is NaN.

This issue arises due to the fact that number.length is undefined, causing Math.max(undefined, x) to evaluate as NaN

Evidently, it seems like you intended to create a function that solely calculates the length of the second argument:

function foo(a, b) {
    return Math.max(a, b.length);
}

In such a scenario, you would obtain the following outcomes:

  1. foo(0, "i am a boy") yields 10
  2. foo(10, " she loves cats") produces 15
  3. foo(15, " a goat ate my flower garden ")
    results in 29

Hence, the final result will be 29.

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

Initiate an asynchronous request from JavaScript to a C# controller located in a separate directory

Note: Updated at the bottom of question I'm encountering difficulties with making an AJAX call from JavaScript to the C# Controller. The issue seems to be related to the connection URL in my AJAX call within the JavaScript file. If the URL isn't ...

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

Decode JSON and generate a user-friendly Array

My aim is to extract and organize the JSON data received from an external API into a custom array. However, I am encountering two challenges: I'm struggling to access the value labeled #2 under "Meta Data". If I want to extract the first array n ...

Losing focus issue with Material-UI TextField occurs constantly with every onChange event

I am in the process of developing a new component: https://i.stack.imgur.com/czM9i.png This component will consist of an array of objects, each representing a prescription. Each object will include the medicine name selected from a dropdown and a text fi ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Reversing data in Vue3

I've been struggling to create a custom dropdown for my application. I need to implement a function that adds a class called is-active to a div element. So, what I have done is created a simple div with an onclick function as shown below: <div :cla ...

What could be the reason behind the success of my API call in Chrome while encountering failure when implemented in my

I'm attempting to access the Binance API in order to obtain the current price of Litecoin (LTC) in Bitcoin (BTC). For this purpose, I have tested the following URL on my web browser: "https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC". Now, I ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Encountering a theme issue in the makeStyles function within Material-UI version 5

While working on some React components, I created a styles.js file for each of them. I am following a YouTube tutorial that uses material-ui version 4, so I decided to upgrade to V5. Code snippet for the component (Form): import React from 'react&apo ...

How can you use JavaScript to identify resize or zoom changes across all ancestor DOM elements?

I have a DOM element that consists of a chart. <div id="plot1" class='plot-chart'></div> This specific DIV can be nested within various other DIVs. <div id="one" style="width:100%;height:100%;zoom:0.9;"> <div id="two"& ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Stryker score caused the Jenkins build to fail

Is there a way to configure the Jenkins pipeline so that it fails when the stryker score is below X? This is the stryker configuration: config.set({ mutator: "javascript", mutate: [...], testRunner: "jest", jest: { projectType: "n ...

Add a pair of assorted div elements to a shared container

I have two different sections with classes named "red" and "blue". By default, these sections are hidden. I want to duplicate them and display them in a single container named "cont". The red button appends the red section and the blue button appends the b ...

The port is not defined in the express when running with the command "node ."

After going through the tutorial mentioned here, everything was smooth sailing until I reached the part where I had to run the server: https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript Attempting to execute the cod ...

What is the process for configuring the injector in my application?

https://code.angularjs.org/1.0.0rc9/angular-1.0.0rc9.js I am facing an issue with the above link as it defines an external js file that I am not familiar with the injector to angular-1.0.0rc9.js. Due to this, my app is not running in the browser. Here is ...

Tips on obtaining outcome by invoking a route outside of app.js

Within my file containing the request methods, the structure appears as follows: article.js router .route("/") .all((req, res) => { console.log("this should happen for any call to the article route"); }) .get((req, res) = ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

Why is the axios.get promise not getting resolved?

I am currently working on fetching data from MongoDB atlas within a React app. However, despite using .then and .catch with axios.get(), I am encountering an unresolved promise. Here is the code snippet: const entry = axios.get('http://localhost:3001 ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...