Resolving array replacement problems in Google Scripts

I've been working on a Google Sheets extension where the script analyzes data in a table structured like this: "A" | "B" | "C" | "E~F"

My goal is to split the strings in column four by the "~" symbol and create two arrays for each row. The final array should have one value from columns A, B, C, and either E or F. Here's what I'm trying to achieve: [["A","B","C","E"],["A","B","C","F"]] While this seems simple in theory, I'm running into an issue where appending my arrays ends up duplicating the second element like this: [["A","B","C","F"],["A","B","C","F"]]. It's important to note that column E may have varying numbers of elements in the future. Any guidance would be greatly appreciated!

var rangeArr=[["BF-A", "true", 'A kind reminder to make a weather report if you are on duty today', 'Something','2.0', 'Humphrey Bogart~James Dean'], ['BF-B', 'true', 'Kindly report on the condition of the BF now', 'Something else', '4.0', 'Humphrey Bogart~James Dean'], ['R-A6', 'true','A kind reminder to report on the reservoir level', 'Something completely different', '1.0', 'Angela Merkel']];
var newArr=[[]];

var count=0;
for(i in rangeArr){
    var str=rangeArr[i][5];
    var places=str.split("~");
    var otherThings=rangeArr[i].slice();
    otherThings.pop()
    for (a in places){
        otherThings[5]=places[a]
        var nextThing=otherThings.slice();
        newArr[count]=nextThing;
        count=count+1;      
    }
}
alert(newArr)

Answer №1

After some trial and error, I managed to find a solution. It appears that my understanding of JavaScript arrays is not in-depth enough to figure out why the initial code didn't work. Instead of simply appending an element to the original array, I decided to merge elements from two separate arrays into a new one.

var rangeArr=[["BF-A", "true", 'A kind reminder to make a weather report if you are on duty today', 'Something','2.0', 'Humphrey Bogart~James Dean'], ['BF-B', 'true', 'Kindly report on the condition of the BF now', 'Something else', '4.0', 'Humphrey Bogart~James Dean'], ['R-A6', 'true','A kind reminder to report on the reservoir level', 'Something completely different', '1.0', 'Angela Merkel']];
  var newArr=[[]];

  var count=0;
  for(i=0; i<rangeArr.length; i++){
    var str=rangeArr[i][5];
    var places=str.split("~");
    var otherThings=rangeArr[i]; 
    otherThings.pop()
    for (a=0; a<places.length; a++){
      newArr[newArr.length]=[otherThings[1],otherThings[2],otherThings[3],otherThings[4],places[a]]
      count=count+1;
        
      }
  }

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

Retrieving information from MongoDB for a specific ObjectID associated with the current authenticated user

Having two collections in my MongoDB structured as follows: Data User: id: ObjectId ("5fb39e3d11eaad3e30cfb1b0") userName: "Tobias" password: "yyy" id: ObjectId ("5fb3c83fb774ff3340482250") userName: "Thor&qu ...

Tips for positioning elements in a way that prevents CSS fixed from overlapping upon page loading

Is there a way to adjust my navigation menu to prevent overlap upon page load, but have it overlap when scrolling down (Dynamic nav bar)? Check out my current setup: Upon initial page load, the navigation bar overlaps the text. I would like the navigatio ...

Batch download files as a zip file using JavaScript

Is there a straightforward method in JavaScript to download multiple files from URLs and save them as a zip archive? Which specific files are required for downloading in order to generate the zip file? ...

Utilizing AJAX for XML data parsing

I need help with formatting XML data into a table. The code I've written isn't working as expected. The XML data is structured in branches, causing it to not display correctly. Can someone assist me in fixing this issue? <!DOCTYPE html> &l ...

What causes the disparity in functionality between simple html and css in an Angular 2 project compared to a vanilla html website?

When incorporating the following html/css into a new Angular project created with Angular CLI using 'ng new ProjectName', I encountered issues. Despite adding the CSS to app.component.css or styles.css and the HTML to app.component.html, the Angu ...

Transforming JSON keys in Angular

As a newcomer to angular and API integration, I am facing an issue with ngCharts in my project. The chart specifically requires the keys names in JSON to be "value" and "name", but the API I am using provides keys named "count" and "label". Is there a way ...

Error in Angular unit testing: Unable to access the 'subscribe' property as it is undefined

Currently, I am working on a starter kit template that includes authentication and an example with CRUD operations. You can find the code here: https://github.com/fransyozef/basic-login-angular Although I am new to unit testing, I am trying to set up test ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

ASP.Net does not support the compilation of AngularJS

Good Evening! I've been struggling with implementing an ASP.NET API, as my angular code seems to be not compiling correctly. I recently set up a new empty web project, installed angular and jquery through NUGET, and now I'm facing issues while ...

Using reduce() to group items in an array based on a specific object property

Creating a new array grouped by the property 'desc' of the objects within an existing array is my current task. Here is how I envision it: const sourceArray = [ { id: 'id1', sourceDesc: 'foo', prop1: 'ignoreme', p ...

Set the title attribute according to the content of the <p> tag

Recently, I encountered a situation where I had numerous p tags with a specific class (let's call it .text). My task was to include the title attribute containing the text of each tag. For example: <p> Hello, world </p> This would resul ...

Ensure the detection of 404 error status using jQuery

My current approach involves using this code snippet to retrieve data from Twitter through its API: $.ajax({ url : apiUrl, cache : false, crossDomain: true, dataType: "jsonp", success : f ...

Express app encountering duplicated request parameter in URL

Snippet from the app.js file: var contact = require('./routes/contact'); app.all('/:lang/*', function(req, res, next){ var selectedLang = req.params.lang; i18n.setLocale([req, res.locals], selectedLang); res.locals.language = se ...

Is there a way to retrieve the value of a particular attribute while hovering the mouse over it?

When I hover my mouse over the innerHTML content, certain words are highlighted with a title attribute value. How can I retrieve the specific title value of the content I am hovering over? This should be done using the mouseover event in the TypeScript fil ...

Removing solely the selected item, leaving the rest of the elements on the canvas untouched

Just starting out with coding and working on a game for a school project. The idea is to have random circles or "targets" appear on the screen, and the user has to click them. I've been struggling with keeping the "un-clicked" circles on the canvas wh ...

Comparison between Node and React: the role of functions in JavaScript modules

In my setup, there is a Node server that includes a utils file structured as follows: update = () => { // }; module.exports = { update }; Although this works smoothly with the Node environment, I encountered an issue when trying to use the same fil ...

I am looking for a custom script for a splash page that will automatically redirect users to one of three designated pages based on the information stored

As a programmer, I'm well-versed in coding but lack knowledge about creating and utilizing cookies. If anyone could provide guidance on this matter, it would be highly appreciated. I believe I require two concise scripts for this task. 1st Script: T ...

I'm having trouble getting my CSS opacity to smoothly transition back to its original state of .5 using setTimeout(). What could be

I recently started learning JS, Jquery, and CSS. My goal is to create a Simon Says style game. However, when I attempt to animate the computer to automatically light up the correct square, I faced some challenges. To address this issue, I decided to star ...

Placing a document.write statement inside the load function of a fresh Dashcode template prevents the generation of the remaining JavaScript code

I've been working on a new custom safari template using dashcode ("This template creates a blank web application, ready for customizing."). In the process, I noticed that it automatically generates a function called load in main.js that is then called ...

Unable to invoke a function within a JavaScript class

As I develop a THREE.js graphics program, I am looking to create a BodyPart class in Javascript that includes various methods. However, I have encountered an issue where I am unable to successfully call these methods. Despite the code displaying 'call ...