Troubleshooting issue with JavaScript's flatMap() method encountering NaN result during element operation

Hey there, I have a simple query that's giving me some trouble. My goal is to flatten an array with a single layer of depth while also multiplying each element by 2. However, when I attempt to utilize flatMap on arr1, the output in the console displays NaN instead of the expected result: an array containing 5 elements where each one is multiplied by 2. Check out the code snippet below:

const arr1 = [ [2,5] , [5,10,15] ];

const arr2 = arr1.flatMap((el) => el * 2);

console.log(arr2);

Expected // [4, 10, 10, 20, 30]

Actual // [Nan, Nan]

If I run flatMap without the multiplication operation, I successfully retrieve the array with individual elements. It's only upon trying to multiply each value that the NaN issue arises. Can someone help troubleshoot this for me?

const arr3 = arr1.flatMap((el) => el); console.log(arr3);

Actaul // [2,5,5,10,15];

Answer №1

When using the .flatMap() method, the variable el in your callback function represents each element within your array. In this specific scenario, the initial elements will be [2,5], followed by [5,10,15] in subsequent iterations. Multiplying an array with el*2 will result in NaN. Instead, .flatMap() concatenates all arrays returned within the callback into a single resulting array:

const arr1 = [ [2,5] , [5,10,15] ];
const arr2 = arr1.flatMap(inner => inner.map(el => el * 2));
console.log(arr2); // [4, 10, 10, 20, 30]

Answer №2

const arr1 = [ [2,5] , [5,10,15] ];

var flattenedArr = arr1.reduce(function(prev, curr) {
  return prev.concat(curr);
});
console.log(flattenedArr)
const newArr = flattenedArr.flatMap((element) => element * 2);
console.log(newArr)

If you're dealing with nested arrays, make sure to flatten them first before using flatMap. Find out more about how flatMap functions in JavaScript.

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

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...

What are the steps to generate a multiline chart using d3.js with json data specifically formatted for nvd3?

I attempted to create a multi-line chart using nvd3, but encountered roadblocks when trying to make significant modifications. I am considering building my own chart using d3js directly, but I'm finding it challenging to grasp the concept of 'thi ...

What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

Generate dynamic forms utilizing JSON data

I am in the process of developing an application that enables users to answer questions about themselves. The questions are being retrieved from an API. My next step is to generate a form with these questions as entry fields. I am currently utilizing a met ...

Controller method remains inaccessible despite multiple attempts with Javascript ajax Get call

I've tried numerous solutions for this issue, but I'm still unable to make it work. My goal is to invoke a controller method that accepts a parameter and returns a string based on that parameter. Despite using an ajax GET request, the outcome is ...

Troubleshooting the issue of retrieving PHP array value using jQuery.ajax

Utilizing jQuery.ajax to transmit user input to PHP and receive an array in return has been successful. However, upon trying to access a specific element of the array, I encounter an error stating it is undefined. How can I properly access individual eleme ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Invoking JavaScript function from an Android Activity

I have a simple JS function that is supposed to set values of some html contents, but it doesn't seem to be working properly. Here is the code for the JS function: function SetEdits(name,email,pic,date) { document.getElementById("myPic").src=pic; doc ...

Guide to retrieving account information from a MySQL database

I am currently developing a web application utilizing a three-tier architecture with express and docker. I am integrating mysql as the database to store user accounts. Below is my initialize-database.sql file: CREATE TABLE accounts( personId INT NOT N ...

Customizing individual textareas in tinyMCE can easily be done by adjusting the

This resource provides instructions on customizing features like the menubar and status bar for all form fields within tinyMCE: tinymce.init({ selector: "textarea", menubar:false, statusbar: false, .. }); I am wondering how to achieve th ...

How can I conceal the _id field in this MongoDB query?

Is there a way to exclude the _id field from this query using express and node.js? I have created an API with this query, but I need to hide the _id field. Here is the query : router.get("/", (req, res) => { VerbsDE.find({}, { _id: 0 }) .limit( ...

Utilizing multiple class names in Material UI with identical definitions

When working with traditional CSS, it is common to define shared properties between classes like this: .classA,.classB{ background-color: black; } In Material UI and using theming, the equivalent would be: styles = (theme)=>({ classA:{ ba ...

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

Using Javascript, it is possible to generate a new JSON object through manipulation of an already

I have a JSON object that I am manipulating to create a new JSON object. The challenge lies in dynamically constructing a part of the JSON object. Below is the original JSON object: [{"acptFlag":true,"count":14288,"limsFlag":true,"plantId":30,"plantName": ...

The Highchart is failing to display a single data point

The marker I set is not displaying when there is only a single data point available. The data point is only showing up when we hover on the chart. Check out an example fiddle here - jsfiddle ...

Troubleshooting Issue with Formidable Not Working with Multer

Attempting to develop a webpage that enables users to upload a file to a designated folder while specifying a number in an input field. Currently, I am navigating through the Multer library despite typically using body-parser. Referencing both my app.js an ...

When utilizing "Koa-Rewrite," an AssertionError occurs stating that app.use(rewrite) necessitates a generator function

I am currently working with Koa@1 and koa-rewrite@1 to implement a specific functionality. rewritelogic.js const rewrite = require('koa-rewrite'); function rewriteLogic(){ rewrite('/english/experience/dev1', '/english/experienc ...

Fanciful Selective Ionic Directive

I recently started using fancySelect from the Ionic framework for multiple select options. As I am still getting acquainted with Ionic, I encountered an issue where I needed some items in fancySelect to be pre-selected by default. If you want to take a lo ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

Passing data from a child component to a parent component in Vue 3: How

Struggling with Vue 3 app authentication through event-emission from child to parent. Below is a snippet of the code: Child <template> <form class="msform"> <input @click="goToLogin" type="button" name=&q ...