Generating a three-dimensional array from a one-dimensional array using Javascript/Typescript

I am looking to generate a 3D array from a 1D array that I have.

let a = ['hello', 'my', 'friend']

I attempted to create the 3D array with the following code:

b = [[['h'], ['e'], ['l'], ['l'], ['o']], [['m'], ['y']], [['f'], ['r'], ['i'] ,['e'], ['n'], ['d']]]

Unfortunately, it did not work as expected.

Can anyone provide guidance on how to achieve this?

Answer №1

This code snippet leverages the power of the spread operator to automatically trigger the String#[@@iterator]() function for each word, then uses the map() method to transform each character into its individual unit-length array:

let a = ['hello', 'my', 'friend'];
let b = a.map(word => [...word].map(c => [c]));

console.log(JSON.stringify(b));

If you are working with Typescript as a preprocessor and encounter issues, it may be necessary to utilize the generic implementation of the Array#slice() method on each word since they behave like Array-like objects (which Typescript might not recognize):

let slice = Function.call.bind(Array.prototype.slice);

let a = ['hello', 'my', 'friend'];
let b = a.map(word => slice(word).map(c => [c]));

console.log(JSON.stringify(b));

Answer №2

Having two map functions in sequence works perfectly.

let list = ['hello', 'my', 'friend'];

let output = list.map((word) => word.split('')
.map((letter) => [letter]))

console.log(output)

Answer №3

Here is a simpler solution:

function breakStringIntoArray(str){
    var masterArr = [];
    var wordsArray = str.split(" ");
    for(var j=0; j<wordsArray.length; j++){
        var wordArray = wordsArray[j];
        var innerWordArr = [];
        for(var i=0; i<wordArray.length; i++){
            innerWordArr.push([wordArray.charAt(i)]);
        }
        masterArr.push(innerWordArr);
    }
    return masterArr;
} 

Answer №4

The map function in JavaScript will return an array when called, resulting in an array of characters.

a.map(function(item) { return [ item.split('') ]; })
// [[["h","e","l","l","o"]],[["m","y"]],[["f","r","i","e","n","d"]]]

By applying the map function a second time to each character, you can encapsulate each character within its own array.

let b = a.map(function(item) { 
    return item.split('').map(function(inner) { 
                                    return [ inner ]; 
                                }); 
})
// [[["h"],["e"],["l"],["l"],["o"]]],[[["m"],["y"]]],[[["f"],["r"],["i"],["e"],["n"],["d"]]]

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

Encountering issues with accessing 'this' items in the confirmation function of Angular Material's $mdDialog

Attempting to utilize the confirm function within an Angular Material $mdDialog in order to clear an array and then log it to the console is proving problematic. There appears to be an issue with accessing 'this' objects, arrays, expressions, and ...

Struggling with NodeJs POST request issue

Let's imagine I have a specific URL https://exampleAPI.com/authorize?param1=value1&param2=value2 Where param1 and param2 are the payload values being sent. How can I execute a POST request in this particular way? I attempted the following: var ...

Displaying a concealed form or Unveiling a popup dialog

What is the most effective way to display a simple form on an HTML page with a save button that calls a web method? I'm currently contemplating between the following options: Reveal a hidden <div> containing a form with the same functionality ...

Troubleshooting Problem with JQuery Paginate Plugin Alignment

I have implemented jquery ui 1.10.4 on a web application to paginate and display a specific number of items from an ArrayList on a webpage. However, I am facing an issue where the pagination buttons do not adjust their position when the size of the list ch ...

Optimal strategy for Retrofitting all JavaScript files to substitute <myArrayObj>.forEach(iteratorFn) with _.each(<myArrayObj>, iteratorFn)

Looking for the best approach to update all JavaScript files by replacing instances of <myArrayObj>.forEach(iteratorFn) with _.each(<myArrayObj>, iteratorFn) I have a number of older JavaScript files that need updating to ensure compatibility ...

Convert a list to a JSON object utilizing the Json.NET library

I am using json.net to convert currency rates to JSON format. In the C# entity, there are Name and Value properties; where Name represents currencies like USD, GBP, etc. and Value holds the currency rate. Since I do not know the index of different curren ...

populating information to compress using Javascript

I am facing an issue with my button. I want to be able to click on it and have the data populate in the collapse using JavaScript, but for some reason it is not working. The collapse functionality is working fine when I click the button, so there is no pr ...

How can I detect when an image is loaded in a specific container division using jQuery?

I have a container with multiple images inside, and I would like to capture an event each time an image finishes loading. For example: <div id="container"> <img src="..." /> <img src="..." /> <img src="..." /> ...

Assurance that request does not result in any value being returned

I have come across this interesting challenge: function getAPI(token) { return new Promise((resolve, reject) => { console.log("Requesting API"); GM_xmlhttpRequest({ method: "GET", url: "URL"+token, onload: function(respo ...

JavaScript's getElementById function may return null in certain cases

I am studying JavaScript and I have a question about the following code snippet: document.getElementById('partofid'+variable+number). Why isn't this working? Check out these examples and JSfiddle link. I want the "next" button to remove th ...

Use a loop with requestAnimationFrame to continuously clear the canvas and reset the drawing board

I have been experimenting with creating interactive elements in a canvas using requestAnimationFrame. The issue I am facing is that the function to clear and create a 'blank' canvas space does not seem to be working properly within the loop. From ...

Performing web scraping on a page rendered with Javascript in Python 3.5

I'm currently working on a project that involves extracting a dynamically rendered table using Python 3 and a webdriver. Below is the code I have implemented: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait fro ...

What is the best way to invoke a JavaScript function that utilizes the jQuery library?

Recently I came across this interesting function: function squarifyMe(element) { squareItUp() window.onresize = function(element) { squareItUp(); } function squareItUp() { $(element).height($(element).width()); } } and its usage is as ...

Modify CSS using JavaScript at a specific screen size

Currently, I am in the process of designing a responsive navigation system which involves implementing a button that dynamically changes the styling of the div #navigation using Javascript. The aim is to toggle between display: none; and display: block; ba ...

Styling HTML Select Box Options

My goal is to display the user's name and email within an option of a select box: <option>Adda <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caabaeaeab8aafb2aba7baa6">[email protected]</a></option& ...

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

Encountering a post AJAX issue in Spring JAVA

I have successfully implemented MVC spring and now I want to consume it with SAPUI5 (javascript) using AJAX. However, I encountered an error "415 (Unsupported Media Type)". I have used swagger in spring to test CRUD operations. In swagger, I was able to in ...

Identify matching values in objects and dynamically update them with a custom value

I have an array structured like this: var array = [ { dates: "2020-12-25", class: "first" }, { dates: "2020-12-26", class: "last" }, { dates: "2021-06-11", class: "first" }, ...

Displaying dynamic SVG with AngularJS

Trying to generate an SVG based on data from the scope, but encountering issues with rendering - it comes out empty or displays 'NaN' for some unknown reason. https://i.sstatic.net/vO70i.png Additionally, errors are popping up right after the r ...

The Datatable feature is malfunctioning, unable to function properly with Javascript and JQuery

As a novice in the world of jquery/javascript, I find myself struggling with what may seem like an obvious issue. Despite following tutorials closely (the code for the problematic section can be found at jsfiddle.net/wqbd6qeL), I am unable to get it to wor ...