The functionality of the JavaScript Array Map function is not meeting our expectations

I am encountering an issue with the Array.map function that is not behaving as expected. Below is a simplified example to help me understand where I am going wrong.

Here is the code snippet in question:

console.log(this.reportTestData)
let data = this.reportTestData.map((row) => {
    return [ 1 , 2, 3]
});
console.log(data)
return data

Upon logging this.reportTestData, it is an array with 92 objects, where the content of each object is not relevant:

https://i.sstatic.net/ZOm54.png

Based on the code, I expected the map function to iterate over the array 92 times and produce a new array ([1,2,3]) for each element. This should result in an array of 92 elements, with each element being a [1,2,3] array. However, this is not the output I am receiving.

https://i.sstatic.net/xKwbY.png

Instead of an array with filled elements, I am getting an array of 92 empty elements.

As an alternative, I also attempted to return objects from the map function:

 console.log(this.reportTestData)
 let data = this.reportTestData.map((col) => {
     return { test : 1 }
 });
 console.log(data)
 return data

However, even in this case, I am getting empty objects without any properties:

https://i.sstatic.net/taTNU.png

Any assistance in identifying where my mistake lies would be highly appreciated, as I am unable to pinpoint the error myself.

Answer №1

After experimenting with 10 items in an array, it is evident that the map function is effectively running for each element, as shown by the 10 occurrences of [1,2,3].

let reportTestData = [1,2,3,4,5,6,7,8,9,10]
console.log(reportTestData)
let data = reportTestData.map((item) => [ 1 , 2, 3]);
console.log(data)

Continuing the test with an array containing 10 objects:

let reportTestData = [{},{},{},{},{},{},{},{},{},{}]
console.log(reportTestData)
let data = reportTestData.map((item) => [ 1 , 2, 3]);
console.log(data)

The map function of Arrays successfully operates in this scenario as well. It is crucial to review your code to identify any errors that may be affecting its performance.

Answer №2

That solution works perfectly for me!

const testArray = new Array(12).fill(0);
let result1 = testArray.map((row) => {
    return [ 1 , 2, 3]
});
console.log(result1)

let result2 = testArray.map((row) => {
    return { test : 1 }
});
console.log(result2)

https://i.sstatic.net/ucOQ6.png

https://i.sstatic.net/F0tDP.png

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

Implementing onClick functionality in RecyclerView post JSON data extraction

I recently implemented a RecyclerView in a fragment and successfully parsed JSON data from a website to display it in the RecyclerView following a helpful tutorial found at: Now, my next challenge is adding an onClick listener to the items in the Recycler ...

Issue with React Redux: Passing down a component's method to its children results in an undefined error

Currently, I am working on creating a todo list using React and Redux. In my code snippet provided below, there is a component that includes a function called onDeleteItem. The issue I am facing is the inability to pass the onDeleteItem function to the s ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Organizing data in a database the arrangement way

I'm looking to populate an array with values for "name" and "nickname" extracted from an SQLITE database and then display them in an alert box. This task is part of a JavaScript project developed using Titanium Appcelerator. Below is the code snippe ...

What is the best way to incorporate multiple input boxes into a single alertbox for repeated use?

I attempted to use the same alertbox for 3 different input elements by converting it into a class and using getElementsByClassName, but unfortunately, it did not work as expected. Here is what I tried: <input type="text" class="form-control date notif" ...

The validations continue to function properly even when HTML has been removed

In my form, I have implemented an "addmore" functionality that allows users to dynamically add a set of HTML input fields. Users can also remove the added rows if needed. While everything is functioning correctly, I am encountering an issue where validatio ...

Do not directly change a prop - VueJS Datatable

Just starting out on Vue JS and encountered an issue while trying to create a Data Table by passing parent props to child components. An Error Occurred: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent ...

I attempted to upload an image using the Google Drive API, but encountered an error in the response

I am attempting to upload an image using the Google Drive API, but I encountered an error in the response message. The error reads as follows: "Failed to load resource: the server responded with a status of 403 ()" ...

Utilizing jQuery.post to generate a dynamic dropdown menu

I recently designed a dropdown list that functions well on a standalone page. However, I encountered an issue when attempting to display it in a table on another page using jQuery.post(). The contents appear to overflow from the dropdown list. The jQuery ...

Tips for creating responsive content within an iframe

I have inserted a player from a website that streams a channel using an iframe. While I have managed to make the iframe responsive, the video player inside the iframe does not adapt to changes in viewport size. Despite trying various solutions found online ...

Tips for aligning two objects side by side in HTML

Apologies for the basic question, forgive my ignorance but I am struggling with keeping two objects in the same line within the same division. Please take a look at the code below: <html> <head> <style> .search-input { width: ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...

Transforming an array into key-value pairs where the keys are odd elements and the values are even elements

Is there a straightforward way to transform this initial array: [ "Bargain", "deal", "Consistent", "Steady; regular", "Accurately", "a thing bought or offered for sale much more cheaply than is usual or expected.", "Charge", "demand (an am ...

ag-Grid incorporating new style elements

For my Angular application, I have a simple requirement of adding a CSS class when a row expands or collapses to highlight the row. I attempted to use gridOptions.getRowClass following the documentation at https://www.ag-grid.com/javascript-grid-row-styles ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

Guide for incorporating Google maps into a Vue.js application

Can anyone help me with displaying a Google map using Vue.js? I've tried but it's not showing up, and there are no errors in the console. Below is the code I'm using, and I need to display the map within that specific div tag. <template& ...

PostgreSQL dynamic query with Node.js

I am currently developing a note-taking app using REACT. My focus is on tracking only the changes made by the user to the note, rather than the current state of the note. For properties that have not been altered, I intend to send them as an empty string ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...