Adding an array to a nested array

In my Google Apps Script project, I am facing a challenge while trying to insert an array into another array. The scenario involves extracting data from a spreadsheet, which is essentially an array of arrays. I then have to compare this data with another array and store the corresponding values in a new array. The catch is that the new array needs to maintain the same structure as the original one. However, I'm struggling to achieve this desired result. My attempts to 'push' the matched array elements either result in a single large array or multiple smaller arrays that don't align with the original structure. Furthermore, when I tried using an index based on the loop of the original array, I encountered a 'TypeError'.

  /*
    Step 1 - Read All Data Into An Array

  */

  //Gets Client Data For Each Firm
  mysheet = ss.getSheetByName(sheetNames[1]); //Adjusted worksheet
  ss.setActiveSheet(mysheet);
  arrInput = ss.getRangeByName(rngNameRawClientType).getValues(); 

  //Gets Client Classifcation and Score Data 
  mysheet = ss.getSheetByName(sheetNames[2]); //Data Validation worksheet
  ss.setActiveSheet(mysheet);
  arrClassification = ss.getRangeByName(rngNameClient).getValues();

  /*

    Step 2 - Perform Calculations on the Data

  */

   //Iterate Through Raw Data Input Array (Rows) 
   for(var r = 0; r < arrInput.length; r++) {

    //Iterate Through Column of Each Row
    for(var c = 0; c < arrInput[r].length; c++) {
       var strClientType = arrInput[r][c];

      //Compare To Classification Array - Return Corresponding Score
      var matchScores = [];
      for(var z = 0; z < arrClassification.length-1; z++) {
        if(arrClassification[z][0] === strClientType) {          
          //Add Score to Scores Array
          matchScores.push(arrClassification[z][1]);       
        }
      }
    }
     scores.push(matchScores);

Answer №1

To properly handle the values in the for-loops, it is important to initialize an empty array (scoreRow) and push the value into that array each time the variable `c` is increased. Once you have completed this step, make sure to use scores.push(scoreRow) every time the variable `r` is incremented.

for(var r = 0; r < arrInput.length; r++) {
  var scoreRow = []
  //Loop Through Column of Each Row
  for(var c = 0; c < arrInput[r].length; c++) {
    var strClientType = arrInput[r][c];

    //Check Against Classification Array - Get Matching Score
    var matchScores = [];
    for(var z = 0; z < arrClassification.length-1; z++) {
      if(arrClassification[z][0] === strClientType) {          
        //Include Score in Scores Array
        matchScores.push(arrClassification[z][1]);       
      }
    }
    scoreRow.push(matchScores);
  }
  scores.push(scoreRow);
}

Answer №2

const filterData = (data, filters) =>
  data.map((column) => 
    column.filter((row) => 
      !filters.includes(row)))



const inputData = [
  ['a', 'b', 'c'],
  ['a', 'b', 'c'],
  ['a', 'b', 'c'],
  ['a', 'b', 'c']
]
const inputFilters = ['b']

const output = filterData(inputData, inputFilters)



console.log(output)

I believe this code snippet fits your requirements. It is utilizing ES6 syntax.

(Arrow) Function filterData takes two parameters: the input data and specified filters.

Array map generates a new array during each iteration

Array filter produces a new array based on the conditions inside

Array includes called with row as an argument from the filters

I hope this explanation clarifies things for you!

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

React: troubleshooting error of empty object displayed by console log

Just diving into the world of React and facing a challenge with importing a list of objects from a JS file to set them as the initial state of my app. Here's what I've tried: import allSamples from './reducers/reducerSamples'; var App ...

What is the process for determining the directory in which CKEditor looks for configuration and language files?

When CKEditor is loaded on a page, it searches for its configuration files relative to the location where it was initially loaded from, rather than the location of ckeditor.js. For example, loading CKEditor on the page http://www.example.com/articles/1 wou ...

Issue with Primeng 16: carousel styles failing to load properly

I am working on a straightforward project using Angular and Primeng 16. Currently, I have implemented a carousel, and everything seems to be working fine. However, when I try to navigate using the next or prev buttons, the information does not load. I ha ...

What is the best way to incorporate AJAX with Node.js?

After testing the Hello world program with Node.js, I can confirm that it is working perfectly. Here are the file details: index.html socket.js To run in command prompt: node socket.js I also experimented with ajax calls in Node.js using the same hel ...

Learn how to effectively showcase various components by leveraging the new react-router-dom v6.0.0 alongside react-redux

My issue is that when I click on a link to render different components, the URL updates but the UI remains unchanged. No matter which item I click on to render, the same thing happens. I've tried numerous solutions to fix this problem without success. ...

Leveraging union types in Mongoose and typescript: Accessing data from a populated field with multiple value options

In my codebase, I have the following models: CoupleModel.ts import mongoose, { Model, Schema } from 'mongoose'; import { CoupleType } from '../types/coupleTypes'; const coupleSchema = new Schema( { user1: { t ...

Combining Angular JS 1 and Laravel 5.2 for seamless integration

Currently, I am in the process of setting up Angular JS 1 with Laravel 5.2 by installing the necessary dependencies using npm. After installation, a node_modules folder was created alongside the app directory. My primary concern is whether it is recommend ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Error encountered when retrieving data with Django and Ajax

I have a model called Item and I'm attempting to use Ajax to create Items. Everything appears to be functioning correctly, but I encounter an error at the end of the process within the success function of Ajax. Despite reading numerous answers on Stac ...

Trouble with the back button functionality following logout

Despite hours of research and following various links, I am still experiencing a problem where my page continues to load after logging out and clicking the back button. Below is the code I have tried for my log out page: protected void Page_Load(object se ...

Manipulate the lines in an HTML map and showcase the distinctions between them

I've been searching through various inquiries on this particular subject, but none have provided me with a satisfactory response. I have created a map where I've set up 4 axes using the following code: function axis() { var bounds = ...

Three-handled slider

Just acquired a new slider component <input id="slider_price" type="text" class="span2" value="" data-slider-min="1000" data-slider-max="80000" data-slider-step="5" data-slider-value="[60000, 80000]"/> _ $('#slider_price').slider({ t ...

Why does my console refuse to log the input entered for the search?

Looking to become proficient in web development, I am attempting to record HTML search queries in the console after storing them in a variable. However, when I try running the search procedure, nothing seems to be displaying in my browser's inspect co ...

Prevent the input from being erased when inserting innerHTML

I have been developing a form that allows users to dynamically add extra input fields by clicking on a button. The structure of the form is as follows: <div> <input type="text" placeholder="existing"/> </div> <button class="add"& ...

riddle: the worth inside the sealed envelope alters

When it comes to geocoding, I rely on http://tile.cloudmade.com/wml/latest/web-maps-lite.js. I have an array filled with approximately 20 addresses. addresses[n] = {where:where,who:who,contact:contact,note:note,type:type}; My process involves looping th ...

Exploring Inner Elements with jQuery Click Function

Here is a link to my interactive code example: http://jsfiddle.net/zqegh7yz/1/. The HTML markup in the example looks like this: <ul class="list"> <li class="clickable">item 1 <ul> <li>subitem 1</li> ...

What is the process for transferring a JavaScript variable to a Java servlet?

I am trying to send a JavaScript variable to a Java servlet in a web application I am developing. Below is the HTML code: <p id="test">Some text</p> Here is the JavaScript code I am using: var myVar = document.getElementById('test' ...

Retrieving the current window handle using Selenium WebDriver in Javascript

After receiving assistance from engineering, I have made some modifications to my code for grabbing the new window handle. Here is the final version: localdriver = @driver @driver.getAllWindowHandles() .then (handles) -> localdriver.switchTo().wind ...

Setting a predefined value in a dropdown menu can be a challenge, especially when the default value is hardcoded in

I am working with a dropdown and I want to make All Patients the default value. <select [(ngModel)]="searchModel.careprovider"> <option [value]="0">All Pateints</option> <option *ngFor="let user of practiceUsers" [valu ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...