Executing the split function on a 2D array in Google Apps Script while maintaining the original column indexing

When running the split function on an array column in Google Apps Script, it generates multiple columns with varying numbers. Some rows may have 6 columns and others only 4.

I want to adjust the output array to ensure all rows have an even number of columns. This means extending those rows with fewer columns by adding empty spaces in the extra columns.

How can I incorporate this into my equation? Currently, I am using the following formula:

var splitarray = originalarray.map(function(row){ return row[0].split(" ") });

If I log this variable, the result might look like this:

[[1,2,3],
 [1,2,3,4]]

However, I would like the output to be (in this example):

[[1,2,3,],
 [1,2,3,4]]

This way, all arrays will have the same number of columns.

P.S. I am aware that this modification could be made within the spreadsheet itself, but this specific task is part of a larger script operation I am working on.

Answer №1

  • Determine the maximum size of rows in a map
  • Adjust the length of each row based on the calculated maximum size

const originalarray = [["1,2,3"],["1,2,3,4"]];
let maxSplit = 0;
const splitarray = originalarray.map(function (row){ 
    const s =  row[0].split(",");
    maxSplit = Math.max(maxSplit, s.length);
    return s;
});
splitarray.forEach(row=>row.length=maxSplit);
console.info(splitarray)

  • When using setValues(array2D), undefined will be interpreted as null, resulting in an empty cell

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: React.js - The specified element type is invalid

After setting up routing using react-router and trying to access the URL, I encountered an error message saying "Element type is invalid." Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for compos ...

Issue with dynamically filling a form field using ValidityState

I have been utilizing the ValidityState interface for client-side form validation, but I've encountered an issue. Whenever my form is populated programmatically, such as after making a call to a third-party API, the tooLong state always returns false, ...

Exploring the power of async/await in combination with map or foreach

I am facing a challenge in retrieving multiple product prices from my database. I had initially thought of using the map or forEach methods to iterate through them and add up the prices to a variable as shown below: // Get Total exports.getTotal = (req,re ...

Using a function from one class within another class by passing it as a prop

Below are the methods found in my Search.tsx class. renderSuggestion(suggestion) { <div className="buttons"> <button className="button">View Location</button> <button className="button whitebutton" onClick={this.h ...

Create an additional column in HTML using Bootstrap styling

I am currently working on a CRUD form (using PHPMyAdmin for the database), developed in HTML, JavaScript, and PHP. The queries are executed using jQuery. I am facing an issue with my code - whenever I add a new column to my table, the formatting gets messe ...

Trouble with the drop-down menu displaying "string:2" in an AngularJS application

Currently, I am utilizing AngularJS ng-model to choose the value from a drop-down menu. Additionally, I am implementing datatable for organizing the columns. <select id="{{user.id}}" ng-model="user.commit" name="options" ng-change="update_commit_level ...

What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to ha ...

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Understanding the functionality of imports within modules imported into Angular

I have been scouring through the documentation trying to understand the functionality of the import statement in JavaScript, specifically within the Angular framework. While I grasp the basic concept that it imports modules from other files containing expo ...

The Div overlay vanishes once the Javascript function is finished running

Initially, take a look at this fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/ My attempt to run JS on the fiddle has been unsuccessful, but all my code is present there, so we should be fine. I was creating my own custom image viewer, and everything was ...

When using jQuery, remember to encode square brackets in order to target specific

Imagine an input element <input id="meta[152][value]" type="text" /> In this case, the input field is created on-the-fly. I must choose that particular field. That's why I used, alert($('#meta[152][value]').val()); However, it appe ...

Preventing scrolling on a YouTube video embed

I have been working hard on developing my personal website. One issue I encountered is that when there is a YouTube video embedded in the site, it stops scrolling when I hover over it. I would like the main document to continue scrolling even if the mouse ...

The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150 ...

Customizing the design of vuetify table header to your liking

My goal is to implement a custom style for v-data table headers using the fixHeader method. The CSS code is intended to keep the header fixed in place even when scrolling horizontally. The issue arises as the style is applied to the inner <span> ele ...

JSON autocomplete feature for text input field

I've been struggling to implement an autocomplete textbox that utilizes a JSON file as its data source. Currently, the app is hosted on Google App Engine and the autocomplete function is based on an array of countries hardcoded into the code. However, ...

Passing null as a parameter in ngResource AngularJS

I am currently utilizing ngResource from AngularJS 1.2.1, and I'm encountering an issue when attempting to include null as a parameter value in a PUT request. It seems that Angular ignores the parameter entirely and does not send it along with the req ...

Combining various functions into a single button

I am currently working on creating a full-screen menu that functions like a modal. Everything seems to be working fine, except for the fadeOut animation. Can someone please help me understand what is causing issues with my scripts/codes? I want the content ...

Determine the quantity of cells in a row that have identical values, and then save the corresponding coordinates

I am in the initial stages of developing a C# Crozzle game as a beginner. Currently, my main challenge lies in identifying available space within a two-dimensional array that could potentially accommodate a word. Consider the following example array: [ 0 ...

Is there a way to eliminate the quotes from the JavaScript output?

I've gathered data in the following format: [ 0: {latitude: "0", longitude: "0", user_country_name: "-", user_country_code: "-", total_visitors: 4} 1: {latitude: "-33.867851", longitude: "151.20 ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...