An effective method for converting a string into a two-dimensional array using JavaScript

One challenge I am facing is checking from a string if a specific fruit has the correct amount on a given date. I've managed to achieve this by converting the string into a 2D array and iterating over the columns. While this method works, I can't help but wonder if there's a more efficient way to accomplish this without using 4 for loops.

function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
    for (var j = 0; j < colCount; j++) {
         var temp = rows[i].split(',');
         if (!arr[i]) arr[i] = []
             arr[i][j] = temp[j];
         }
}
for (var i = 1; i < colCount; i++) {
    for (var j = 1; j < rows.length; j++) {
         verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
         }
}

Answer №1

One way to handle this situation is by using the Array.prototype.map method

var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})

The map method goes through each element in an array and applies a function to it, creating a new array as the result.

Here's a way to visualize this process:

function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];

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

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

Troubleshoot: Why is my Google Chrome not playing videos? Uncover the solution with a

I have created a webpage with an HTML video tag that loads dynamically from a JSON file. I am currently using Chrome 50 for this project. The response is successful, and when inspecting the page using Chrome's developer tools, I can see the video tag ...

Press on a specific div to automatically close another div nearby

var app = angular.module('app', []); app.controller('RedCtrl', function($scope) { $scope.OpenRed = function() { $scope.userRed = !$scope.userRed; } $scope.HideRed = function() { $scope.userRed = false; } }); app.dire ...

Vue.JS component containing DOM elements outside of the designated $el scope

Transitioning from a custom front-end framework to Vue is a new adventure for me. Our website is gradually integrating Vue, and as we refactor old components, I've encountered an issue. My question is: Can a component create DOM elements outside of i ...

Handling multiple render calls and rerenders in React function components with setTimeout (best practice for firing multiple times)

Is there a way to optimize the Notification component in my App, so that the setTimeout function is only initialized once even if multiple notifications are pushed into the state? function Notification(props) { console.log("Notification function compone ...

how to implement a delay in closing a window using JavaScript

I am currently developing a Google Chrome extension and I want to express my gratitude to everyone here for tolerating my sometimes silly questions. The functionality of the extension is quite basic but it works smoothly. However, I am facing an issue wher ...

Displaying object properties within another object obtained from an API request in a React component

Dealing with API data can be tricky, especially when there are nested objects involved. I've encountered an error message stating 'undefined is not an object (evaluating 'coin.description.en')', as the description property of the c ...

Is there a way to verify if all the values in an array of objects are identical?

In this scenario, my array consists of entries with identical address IDs but different phone types and numbers. I am in need of assistance with iterating through the array to extract the phone type and number when the address ID matches. I seem to encount ...

Building an HTTP request and response directly from an active socket in a Node.js environment

My current project involves passing HTTP requests to a child process in Node.js. I am struggling with passing the active Socket using child.send('socket', req.socket). Once inside the child process, I need to recreate the HTTP request and respons ...

Obtaining cookies from a separate domain using PHP and JavaScript

Imagine you have a cookie set on first.com, called "user". Now, the goal is to retrieve that cookie on second.com using JavaScript and AJAX. Unfortunately, it's not working as expected and you're receiving xmlHttp.status=0. Here is a sample code ...

guidelines for rendering a Vue component within a Vue file using vue-server-renderer

Starting the rendering component with vuejs is my goal. I currently have a basic node server set up. const Vue = require('vue'); const server = require('express')(); const template = require('fs').readFileSync('index. ...

Error: The function "text.toLowerCase()" is not defined

Whenever I execute the following code, I keep encountering this error message: Uncaught TypeError: text.toLowerCase is not a function const getVisibleExpenses = (expenses, { text, sortBy, startDate, endDate }) => { return expenses.fi ...

Is it possible to trigger the alert message by utilizing this code snippet?

Is it possible to display a message using this function? var start_database = function() { alert('hello'); }; window.setTimeout(start_database, 1000); ...

Transmitting Various Static Files via Express Router

I am currently utilizing the Express router to serve static .html files based on the URL specified in router.get. For example, this code snippet sends the homepage: router.get('/', function(req, res, next) { res.sendFile('index.html&ap ...

Troubleshooting Type Conversion Error in ASP.NET MVC Controller

I have been working on an application that utilizes the following HTML and JavaScript. The user is required to input 5 props and then click on the 'Create' button. Subsequently, the JavaScript code compiles all of these props into a list before s ...

JavaScript Library function in Angular Component throwing Type Error: Function is Not Recognized

I created a custom Javascript library to group together essential functions that many Angular Components require. The library called calcs.js includes functions like this: function calculateCosts(object) { do some stuff..... return answer; } To use t ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Is it possible to load asynchronous JS and then execute functions?

Is there a way to make my script behave like the Google Analytics JavaScript snippet? Here is an example of what I have: (function(d, t) { var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.src = 'myjs.js'; s.par ...

Having trouble dynamically adding HTML elements in JQuery

I am dynamically adding HTML elements during runtime using an AJAX call from a JavaScript file. Currently, I am attempting to use a combo box drop-down element to display a list of data. Here is how I am trying to achieve this in my script: $("#myList") ...

How to deactivate the <a> tag with Ant Design UI Library

Is there a method in the antd UI library to disable a link? The disabled attribute is not supported by the a tag according to MDN. This code snippet works in React but the link remains clickable when using Next.js. <Tooltip title={tooltip}> <a ...