Limit the usage of map() to solely operate on a collection of headers stored within an array generated from a specified range

I need to limit the map functionality to only include columns within the specified range that are also present in the headers list, which is a subset of the values in v[0]. This ensures that only values from columns listed in the headers array will be modified.

function test() {
  var ss  = SpreadsheetApp.getActiveSpreadsheet();  
  var sht = ss.getSheetByName('Elements');  
  var rng = sht.getDataRange();
  var v   = rng.getValues();
  
  var headers = ['Id', 'Label'];
  //headers is a subset of v[0]
  

  //This will work for `all` values of the values
  //values = v.map(x => x.map(y => y==("Networking - 1") ? 1: y));

  values = v.map(x => x.map(y => cols.includes(y) == true && y=="Networking - 1" ? 1 : y))
  
  var sht2 = ss.getSheetByName('AAA');
  sht2.getRange(1,1, v.length, v[0].length).setValues(v);
}

Answer №1

Explanation:

  • To start, identify the column indexes where headers are located within the data. You can achieve this by using the indexOf function on the first row of your data set v, which represents the headers row:

    v[0].indexOf(headers[0])
    v[0].indexOf(headers[1])
    
  • Next, utilize the map method to extract only those specified columns:

    v.map(d=>[d[v[0].indexOf(headers[0])],d[v[0].indexOf(headers[1])]]);
    

Solution:

function test() {
  var ss  = SpreadsheetApp.getActiveSpreadsheet();  
  var sht = ss.getSheetByName('Elements');  
  var rng = sht.getDataRange();
  var v   = rng.getValues();
  
  
  var headers = ['Id', 'Label'];
  //headers comprises a subset of v[0]
  
  v = v.map(d=>[d[v[0].indexOf(headers[0])],d[v[0].indexOf(headers[1])]]); // updated code

  //This logic applies to `all` values within the dataset
  //values = v.map(x => x.map(y => y==("Networking - 1") ? 1: y));

  values = v.map(x => x.map(y => y== cols.includes(y)==true && y=="Networking - 1" ? 1: y))
  
  var sht2 = ss.getSheetByName('AAA');
  sht2.getRange(1,1, v.length, v[0].length).setValues(v);
}

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

Examining a feature by solely utilizing stubs

I've been immersed in writing tests for the past few weeks. In my workplace, we utilize Mocha as our test runner and Chai for assertions, with Sinon for creating stubs. However, there's a recurring issue that's been bothering me. I've w ...

Border becomes dashed when dragging and dropping

I am working on enabling drag and drop functionality for users. When an item is lifted from its original position, a gray dashed box should appear in its place. As the item is moved closer to another spot, the containers adjust to create a target area (gra ...

Transferring sizable JavaScript array to the Web API

I've been grappling with this problem for two days... In my JavaScript code, I have a large array comprising 20,000 rows and 41 columns. This data was initially fetched in JavaScript via an ajax call, as shown below: var dataArray = []; var dataRequ ...

Navigating back to the beginning of the webpage following the completion of a form submission utilizing Master Pages and Ajax

I am having an issue with my ASP.NET 4.0 page where I want to reset it to the top after a form submission so that the validation summary can be displayed properly. The setup involves using Ajax and a master page with the following simplified code: <f ...

Calculate the sum of values in a JSON array response

I recently received a JSON string as part of an API response, and it has the following structure: { "legend_size": 1, "data": { "series": [ "2013-05-01", "2013-05-02" ], "values": { "Sign Up": { "2013-05-05": 10, ...

How can I transfer a PHP variable into a JavaScript variable nested within another PHP variable

After my php/html script generates the image, I am looking to display it without needing to reload the page. I currently call a javascript function within the PHP code to change the image. However, I am unsure how to pass the new image name to this javasc ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

How do I switch the background-image on li hover and revert it back when I move off the li element?

Looking to update the background image of a div upon hovering over a li element? Check out this example here. So far, I've got that part working fine. But now I want the background picture to revert back to its original CSS when I move away from the l ...

Using jQuery to trigger an event when an element is empty or when the element contains children nodes

Is there a way to create a jQuery script that can monitor the children of an element? If the element does not have any children, default scrolling for the entire page is enabled. If the element has children, scrolling for the whole page is disabled. The ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

Challenge with the Table Filtering feature in a React application

Having an issue with the filtering functionality in React and MUI. The problem arises when adding a row first and then attempting to filter - the filter stops working. However, if I filter immediately without adding a row, it works as expected. To reprodu ...

There seems to be an issue with the .html() function in one of my

I'm currently in the process of transitioning my code to Angular and I could use some assistance with creating a directive. Here's what I'm trying to convert: jQuery(document).ready(function ($) { "use strict"; $('#cool-naviga ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

Spring application: Unable to find a handler for portlet request with mode 'view' and phase 'Resource_PHASE'

It seems like everything is set up correctly, but for some reason, my ajax call fails with the error message "No handler found for portlet request: mode 'view', phase 'Resource_PHASE'". The handler URL I'm using is "getAllFruit", ...

How can the '!!user' syntax be utilized? What outcome does this code snippet produce?

I am looking to implement an angular route guard in my application. I came across this code snippet but I am confused about the line where user is mapped to !!user. Can someone explain the purpose of map(user => !!user) in this context? canActivate( ...

In Javascript, navigate to a specific section by scrolling down

Currently, I am in the process of enhancing my portfolio website. My goal is to incorporate a CSS class once the user scrolls to a specific section on the page. (I plan to achieve this using a JavaScript event). One approach I am considering is initially ...

Mastering the utilization of API routes within the Next JS 13 App Router framework

As a newcomer to React JS and Next.js, I recently made the switch from using the Page Router API in Next.js to utilizing the new App Router introduced in Next.js 13. Previously, with the Page Router, creating a single GET request involved nesting your "JS ...

NodeJS rendering method for HTML pages

We are in the process of developing a fully functional social networking website that will resemble popular platforms like Facebook or Instagram. Our plan is to utilize Node.js on the server side and we are currently exploring the best technology for rende ...

What is the fastest way to invoke the driver.quit() method in Selenium?

Is there a way to force close the browser immediately instead of waiting for it to complete loading before calling driver.quit()? ...

Unable to add JSON data to Javascript List Object? Consider using a combination of Node.JS and Firebase for a

router.get('/getMeals',function(req,res){ var mealsList = []; mealsList.push("bar"); mealsRef.on("value",function(data){ data.forEach(function(child){ console.log(child.val()); var newMeal = child ...