What causes the TypeError: 0 is not a function error when using Array.from as a callback for Array.flatMap?

An issue arises when using Array.from as a callback with Array.flatMap, resulting in the error message: "TypeError: 0 is not a function"

const x = ["12"].flatMap(Array.from)
console.log(x)

However, when used as a regular function, Array.from operates normally:

const f = Array.from
console.log(f("12"))

To work around this issue, I discovered a solution:

const x = ["12"].flatMap(e => Array.from(e))
console.log(x)

My questions are:

  1. Why does this error occur?
  2. What makes the error message so unhelpful?

Answer №1

Array.from can accept a maximum of 3 parameters, with the second one being a map function. However, when using .flatMap, it passes the iteration index as the second parameter.

During the first iteration, Array.from will receive 0 as the second parameter, which is not the expected function type for Array.from.

To illustrate this issue more clearly, consider the following snippet:

["12"].flatMap(Array.from);

This line is essentially equivalent to:

Array.from("12", 0, ["12"]);

However, this signature is incorrect for Array.from.

Answer №2

The reason for this issue is that the flatMap function is passing more than one argument to the callback function. The second argument is supposed to be the index of the element, but the Array.from function requires a replacer function in the second argument position. Therefore, in this shortened version, an index is mistakenly passed instead of a proper function.

It's like doing this:

Array.from("12", 0)

Instead of using a correct replacer function like shown below:

console.log(Array.from("12", x => x + x));

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

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

eliminate the script and HTML comment from a designated division

Here is the default code that I need to modify using JavaScript to remove scripts, comments, and some text specifically from this div: I came across this script that removes all scripts, but I only want to remove specific ones from this div: $('scri ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

The @emit event in vue.js is not being received by the parent component

Within my application, there is a form located in the ManageCards component. This form includes a child component called ImageUpload, which emits an image file and its local URL to the parent component: <form class="mb-3"> <div class ...

Inserting line breaks in the data retrieved through AJAX

Utilizing ajax to transfer data from a sophisticated custom field wysiwyg editor. Within the markup provided, I am specifically addressing the div with the 'bio' class. However, upon receiving the data, it is consolidated into one large paragraph ...

Executing PHP Code with an External JavaScript File in an HTML Document

I have a script called initialize_database.js that utilizes JQuery to trigger a PHP script for creating a database and some tables. I made sure the PHP script is working correctly by adding HTML to test it independently, and it performed as expected. Below ...

Not all databases are retrieved in the search query

When I make an API call to get all the Database entries, I am encountering an issue. The response I receive only includes a few databases instead of all of them. async function checkDatabases(item){ if(item.object == 'database') ...

detect mouse click coordinates within an iframe that spans multiple domains

I am currently encountering an issue with tracking click position over a cross-domain iframe. Here is my current code: <div class="poin"> <iframe width="640" height="360" src="http://cross_domain" frameborder="0" allowfullscreen id="video">< ...

Switching the phone formatting from JavaScript to TypeScript

Below is the JavaScript code that I am attempting to convert to TypeScript: /** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value) => { const areaCode = value.substr(0 ...

Determining the Maximum Number of Characters Allowed in a Div Using jQuery

Could anyone provide guidance on how to populate a div with single characters? I want the div to span the width of the viewport. The code to get the width is: $(window).width(); I would like JavaScript to generate HTML similar to this: <div id="text ...

VueJS: components unable to access global variables

I am currently in the process of transitioning my front-end to a gulp-based application. I seem to be encountering some issues with Vue.js as I am facing two errors: [Vue warn]: Property or method "params" is not defined on the instance but referenced dur ...

How to emphasize a clicked hyperlink in AngularJS

Here's the HTML code I've been working on: <div id="Navigation" class="md-dialog-full"> <div class="products-options"> <a ng-click='addType("Physical")' href="javascript:void(0);"> < ...

Prevent links from being clicked multiple times in Rails using Coffeescript

Please make the following link inactive after it has been clicked once <%= link_to "Submit Order", {:action => "charge"}, class: 'btn btn-primary', id: 'confirmButton' %> To permanently deactivate the link, use the code below ...

Transform a collection of dates and times into a string separated by commas, showing the range of values with hyphens

My task involves handling a list of performance dates for an upcoming event. Here is an example of the array: 2014-01-20 20:00:00 2014-01-21 20:00:00 2014-01-22 14:00:00 2014-01-22 20:00:00 2014-01-23 20:00:00 2014-01-25 20:00:00 2014-01-26 20:00:00 2014- ...

When a specific item is selected from a drop-down menu, text boxes and drop-downs will dynamically appear and change

In the current version of my code, there is a single drop-down menu with three options for the user to select from. If "Complete" is chosen, a text box should appear. If "Abandon" or "Transfer" is selected, a separate drop-down menu needs to be displayed. ...

Setting Vuetify component props dynamically depending on certain conditions

I've implemented a navbar component in my web app using the v-app-bar Vuetify component. However, I'm facing an issue where I need to dynamically set the props of the v-app-bar based on the current page the user is viewing. <v-app-bar absolu ...

Broken links detected in the Full Page Navigation menu on a one-page website

The hyperlinks on this particular page seem to be malfunctioning despite the fact that the li.a tags are correctly targeting specific section IDs. Markup: <header> <a href="#0" class="nav_icon"><i></i></a> </header> ...

Updating the TextField in React Material UI based on the Slider value without affecting the Slider

Is there a way to update the value of a TextField based on the slider, while still allowing manual input in the TextField? I want the TextField to reflect changes from the slider but not vice versa. I attempted making the TextField a controlled component ...

The global variable is inaccessible when invoked within a dynamically generated function

The variable selected is a global one and accessed using this.selected, which reliably returns the correct value. However, when called from a dynamically created function, it returns unknown. onClick: function(val){ for (i = 0; i < positi ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...