A guide on iterating through a multi-dimensional array in Javascript and organizing the results in a specified sequence

Updated on 18th January, 2021 (refer to bold changes)

I'm currently facing difficulties while attempting to iterate through a nested array and then organize the output in a specific order. Can you assist me in finding a solution to make this work or point out any mistakes I might be making?

It seems like there are certain steps missing in my process. For instance, knowing when to break the inner loop and temporarily store the data. However, I'm uncertain about the exact point... It's worth mentioning that the code is meant for use in a Google Apps Script

The dummy data I am working with is structured as follows: I've introduced a new set of keywords to my sample data – "criss cross" and "bob ross".

var keywords =  [ [ ["claude"],["clair"],["carl"], ["criss cross"] ],
                [ ["brad"],["bob"],["bill"], ["bob ross"] ] ];

The expected output that I would like to obtain appears like this:

[ [ [ '[claude] '],["claude"],[ '+claude' ] ],
[ [ '[clair]' ],["clair"],[ '+clair' ] ],
[ [ '[carl]' ],["carl"],[ '+carl' ] ],
[ [ '[criss cross]' ],["criss cross"], [ '+criss +cross' ] ],
[ [ '[brad]' ],["brad"],[ '+brad' ] ],
[ [ '[bob]' ],["bob"],[ '+bob' ] ],
[ [ '[bill]' ],["bill"],[ '+bill' ] ],
[ [ '[bob ross]' ],["bob ross"], [ '+bob +ross' ] ] ]

However, the actual output I'm generating is as follows:

[ [ [ '[claude]' ],[ '[clair]' ],[ '[carl]' ],[ '[brad]' ],[ '[bob]' ],[ '[bill]' ] ],
[ ["claude"],["clair"],["carl"],["brad"],["bob"],["bill"] ],
[ '+claude','+clair', '+carl', '+brad', '+bob', '+bill' ] ]

Here's the code I am using:

var keywords =  [[[ "claude"],["clair"],["carl"]],
                [[ "brad"],["bob"],["bill"]]];

var keywords = [].concat.apply( [], keywords );
const PERMUTATION = function permuation( item ) {
    var exact = [];
    var phrase = [];
    var modified = [];
      
    for( let i = 0 ; i < item.length ; i++ ) {
    
      var output1 = "[" + item[i] + "]";
      exact.push([output1]);
    
      var output2 = '"' + item[i] + '"';
      phrase.push([output2]);
    
      var temp = [item[i][0].split(" ").map( i => "+" + i ).join(" ")];
      modified.push(temp);
    }
    return new Array( exact, phrase, modified ) ;
  }

  var output = PERMUTATION(keywords);
  console.log(output)

Answer №1

To achieve the desired style, you can flatten the arrays and then apply the mapping function.

const
    keywords = [[["clau de"], ["clair"], ["carl"]], [["brad"], ["bob"], ["bill"]]],
    result = keywords
        .flat(Infinity)
        .map(v => [`[${v}]`, `"${v}"`, v.split(' ').map(v => `+${v}`).join(' ')].map(v => [v]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

const searchTerms =  [[["sara"],["sam"],["sophie"]],
                [["peter"],["philip"],["penny"]]];

searchTerms.flat(2).reduce((accumulator, term) => {
  const subArray = [ [`[${term}]`], [`"${term}"`], [`+${term}`] ];
        
  return [...accumulator, subArray];
} , []);

Answer №3

Resolution

var names = [
  [["john"], ["joe"], ["james"]],
  [["sarah"], ["susan"], ["samantha"]],
];

let output = names
  .flatMap((i) => i)
  .map((name) =>
    ["[key]", '"key"', "+key"].map((currentName) => [
      currentName.replace(/key/g, name[0]),
    ])
  );

console.log(output);

Answer №4

I'm uncertain about the expected result, but a spreadsheet format similar to this can be created:

A B C D E
1 2 3 4 5
6 7 8 9 10

To achieve this layout, you can use the provided code snippet:

function retrieveData() {
  const info=JSON.stringify(SpreadsheetApp.getActiveSheet().getDataRange().getValues());
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput('<textarea rows="12" cols="60"gt;' + info + '</textarea>'),'Data Output');
}

The output generated will resemble the following structure:

[["A","B","C","D","E"],
[1,2,3,4,5],
[6,7,8,9,10]
<!-- Remaining row data shortened for clarity -->]]

Consider your specific requirements when assessing the resulting information.

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 is the best way to send props to every block in Svelte?

Having some trouble understanding how to work with Svelte's props. I have a component called Assignment that I want to use inside my Board component. I'm looking to pass a dynamic array prop into the {#each} block of my Assignment. <script> ...

The Angular Animation constantly resets with each new action taken

In my Angular project, I am working on a scaling animation for a list. I want the animation to only trigger when specific buttons (red and green) are pressed. Currently, the animation restarts regardless of what I click on. Can anyone help me troubleshoot ...

What is the solution for the error message: "[Vue warn]: Error in mounted hook: 'TypeError: document.getElementById(...) is null'" that appears in the <Root> component?

I'm facing an issue with a checkbox in my Vue.js application. Whenever the user checks this checkbox, the data property accepted changes from false to true. My goal is to hide certain HTML elements when accepted = true. I have been attempting to achi ...

The react-leaflet-heatmap-layer-v3 source directory could not be located

Upon attempting to utilize the npm package react-leaflet-heatmap-layer-v3 in my React TypeScript application, I successfully installed it and ran yarn start. However, I encountered the following warning messages: WARNING in ./node_modules/react-leaflet-hea ...

What is the proper method for transforming an Excel column containing JSON format data into a JavaScript object?

I am facing an issue with converting data from an excel sheet to json format. While the other columns convert successfully, one specific column containing json data is not being converted properly and instead gets treated as a string. Using JSON.parse() on ...

The YYYY-dd-mm input mask pattern is malfunctioning

Hello, I am having trouble creating a pattern for an input field in the format YYYY-mm-dd. My code is not working properly. Can someone please help me correct my code? Any assistance would be greatly appreciated. <html> <head> <title>En ...

Sending target information as a property argument

I have encountered an issue with my app's two Bootstrap modals. It seems that many people are facing problems with opening the second modal. Is it possible to pass data-target and modal id properties as props in this manner: data-target={props.da ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

``I am experiencing an issue with HttpXMLRequest becoming un

I am currently experimenting with the HttpXMLRequest object in JS and have created a basic loop that retrieves name and age data from an XML file to display in a table. The issue I am facing is that if one of the elements is missing from a sibling, the cod ...

The document.ready function does not seem to be functioning properly within an iframe

In the main page, there's an embedded iframe set up like this: <iframe src="facts.php" style="width:320px; height:500px; border:hidden" id="facts"> </iframe> Within that iframe, a jQuery function is implemented as follows: <script ty ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Guide on creating a sitemap using Express.js

I've been working with the sitemap.js package from https://www.npmjs.org/package/sitemap While I can add URLs to the sitemap manually, my challenge lies in adding URLs based on data retrieved from MongoDB. Since fetching data from MongoDB is asynchro ...

Making an Ajax request to retrieve progress information by utilizing IProgress

I have encountered an issue with my code involving 2 ajax API calls. One call fetches data through a lengthy process, while the other retrieves progress values using the IProgress interface and runs every 5 seconds. The value from ReportProgress successf ...

is it possible to adjust the height of a tableRow in mui?

I recently created a table component using Mui. I've been attempting to adjust the height of the tableRows, but so far I haven't had any success. Below is my code snippet: import React, { memo } from "react"; import { ActionItemType, ...

What is the best way to verify the [routerLink] values displayed from an Angular component string array?

I want to display the [routerLink] values coming from a string array in my Angular component. This is the TypeScript code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: & ...

The system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

php json with multiple dimensions

Unable to retrieve the deepest values from my json object, which contains an array of images listed as: { "imgs":[ { "Landscape":{ "2":"DSCF2719.jpg", "3":"DSCF2775.jpg", "4":"IMG_1586.jpg", ...

What is preventing me from transforming a List into an Array?

My project encountered an error that I'm unsure about. Why am I unable to convert a list to type system.array? System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[DataLayer.Appoinment]' to type ...

What is the correct way to outline the parameters for deactivating functions?

Request for Assistance! I am facing a challenge with multiple blocks in my WordPress website. Each block contains a checkbox, two select options, and an element that needs to be toggled based on the selected options in the dropdowns. The functionality to ...