Leverage the power of index to slice through an array in Apps Script

Having recently transitioned from Matlab to apps script, I am facing a challenge with subsetting arrays. Specifically, I need to filter the array "names" based on the values in another array called "index", which are of equal length:

names = [["name1"], ["name2"], ["name3"], ["name4"], ["name5"],["name6"],["name7"],["name8"],["name9"],["name10"]];
index = [0,0,1,0,1,0,0,0,0,1]; 

My goal is to extract only the names from the "names" array where the corresponding index value is 1. I attempted the following code:

var subsetNames = names[index];

Although the code executes without errors, "subsetNames" remains undefined. How can I modify the code to successfully achieve the desired subsetting? Thank you.

Answer №1

Consider this solution as one of the many options for your situation. Feel free to explore other possibilities.

Example code snippet:

var names = [["name1"], ["name2"], ["name3"], ["name4"], ["name5"], ["name6"], ["name7"], ["name8"], ["name9"], ["name10"]];
var index = [0,0,1,0,1,0,0,0,0,1]; 
var subsetNames = names.filter(function(e, i) {return index[i] == 1}); // [["name3"],["name5"],["name10"]]

Note:

  • Make sure that the lengths of both arrays names and index are equal for the script to work correctly.

Additional Resources:

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

What's causing the member to be undefined?

client.on('raw', (e) => { if (e.t === 'MESSAGE_REACTION_ADD' && e.d.message_id === '813150433651851265' && e.d.emoji.name === "✅" ) { const guild = client.guilds.cache.get(e.d.gui ...

Using TypeScript to effectively validate form checkboxes for input fields

I've created a form that includes multiple checkboxes with corresponding input fields. <div class="group-wrap input-element" id="gr_"> <div class="label-bar"> <label> <div class="cust ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Unable to display a dynamic dropdown within a Bootstrap modal

I'm currently delving into JavaScript and seem to be stuck on a rather trivial problem, unsure of what I might be overlooking. My predicament lies within a Bootstrap modal where I aim to dynamically append currency codes and exhibit them in a dropdow ...

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...

Tips on utilizing controllers within AngularJs directives?

In order to utilize a controller in my directive, what is the best way to access all controller functions within the directive? directive.js angular.module('App').directive('deleteButtons', function (prcDeleteFactory,$rootScope) { & ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...

Optional subscripting for arrays in Swift allows for safe and concise

Here is a simple playground code snippet: var array :[Int?] array = [1, 2, 3] array![1] = 4 Encountered an error while running the Playground Playground execution failed: error: :8:1: error: '@lvalue $T6' is not identical to 'Int?' ...

substituting symbols with colorful divs

I'm looking to add some color to my text using specific symbols. (), ||, and ++ are the symbols I'm using. If a text is enclosed in | symbols, it will appear in blue, and so on... Here is the code in action: const text = "|Working on the| i ...

What is the process for adding a naked domain (without www) on GoDaddy that is deployed through Heroku?

I have successfully deployed a domain through Heroku, and it is functioning properly with the www prefix. However, when attempting to access the domain without the www, it fails to render correctly. I have tried adding both versions of the domain (with www ...

How can you identify changes in localstorage and then trigger the activation of a new boot file or reallocate a value using Vue.js or JavaScript?

When users log in, they have the option to choose from 3 domains: dev, demo, and sandbox. The configuration for these domains is set in the Boot.js file using Axios. The boot file is triggered prior to the firing of the Vue instance. Below is the content o ...

Experiencing varying outcomes when using ggplot versus base plot functions

I have an available table which can be downloaded from this link: . My goal is to create a point plot using the data in this table. After reading my table, I execute the following script: res2<-read.table("res2.txt", header = TRUE, sep="\t") I p ...

Invoke the JavaScript function on the HTML button click event, sending the ASP parameter

Currently, I am working with node and passing a parameter in the following manner: res.render('page.ejs',{"product" : product }); The paramter 'product' is in JSON format. Within the 'page.ejs' file, I am attempting to call ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

Activate all chosen CSS circles

I'm currently working on creating a progress bar using CSS circles. The idea is that when you click on each circle in sequence (1, 2, 3), all three circles and the line connecting them will fill up with red color. If you then go back (3, 2, 1), the co ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

guarantee feature functions perfectly on Chrome and Firefox, yet encounters compatibility issues on IE Edge and IE11

I've created a function that seems to work well in Chrome and Firefox, but it's not functioning properly in IE Edge or IE 11: async function getJSONDataWithHeaders(url, methodType, responseType) { return new Promise(async function (r ...

What is the procedure for populating a listbox with items selected from an array?

On my aspx page, there is a listbox (techGroups) with preselected items that users can change. I also have a reset button that should restore the listbox to its original selections when clicked. However, I am encountering an issue where only the first pres ...

When importing modules in node.js, the presence of a function can overwrite another function even if it

Within this code snippet, I am utilizing Express.js. //index.js app.use('/',routes()); //app/routes.js module.exports = function() { express = require('express'); const loggedUserProfileController = require('../controller ...