Retrieving the nth item from a multi-dimensional array using JavaScript

Consider this JavaScript array structure:

let text = [
{
  line: [{
    words: [{
      word: [
        { letter: 'H' },
        { letter: 'i' },
        { letter: ' ' },
      ],
    },
    {
      word: [
        { letter: 'J' },
        { letter: 'i' },
        { letter: '\n' },
      ],
    }],
  }]
},
{
  line: [{
    words: [{
      word: [
        { letter: 'H' },
        { letter: 'i' },
        { letter: ' ' },
      ],
    },
    {
      word: [
        { letter: 'J' },
        { letter: 'o' },
        { letter: '\n' },
      ],
    }],
  }]
}

Is there a quick and easy way to access the nth letter in this array?

  • If n=0, get 'H'
  • If n=1, get 'i'
  • ...
  • If n=11, get 'o'

You can also check out this JSFiddle for reference: https://jsfiddle.net/Imabot/6usdej75/

Answer №1

To enhance efficiency, consider maintaining an index of the object similar to databases for optimal performance.

Answer №2

My solution involved utilizing the flat and flatMap functions:

let text = [
  {
    line: [{
      words: [{
        word: [
          { letter: 'H' },
          { letter: 'i' },
          { letter: ' ' },
        ],
      },
      {
        word: [
          { letter: 'J' },
          { letter: 'i' },
          { letter: 'm' },
          { letter: '\n' },
        ],
      }],
    }]
  },
  {
    line: [{
      words: [{
        word: [
          { letter: 'H' },
          { letter: 'i' },
          { letter: ' ' },
        ],
      },
      {
        word: [
          { letter: 'J' },
          { letter: 'o' },
          { letter: '\n' },
        ],
      }],
    }]
  }
];

const flat = text.map(({ line }) => line.map(({ words }) => words.map(({ word }) => word)).flatMap(item => item.flat())).flat();
function getIndex(array, index) {
  return array[index];
}
console.log(getIndex(flat, 0));
console.log(getIndex(flat, 1));
console.log(getIndex(flat, 11));

Answer №3

To achieve your goal, I suggest utilizing a loop to pinpoint the specific index where you want to break the text:

let content = [
{
  line: [{
    words: [{
      word: [
        { letter: 'H' },
        { letter: 'e' },
        { letter: 'l' },
        { letter: 'l' },
        { letter: 'o' },
      ],
    }],
  }]
}];
console.log( findLetter(content, 0) );
console.log( findLetter(content, 1) );

function findLetter(textArray = [], targetIndex = 0) {
  let currentCount = 0;
  for (let {line} of textArray) {
    for (let {words} of line) {
      for (let {word} of words) {
        if (word.length + currentCount <= targetIndex) {
          currentCount += word.length;
        } else {
          return word[targetIndex - currentCount].letter;
        }
      }
    }
  }
}

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

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Determine which file to load based on the size of the browser

I have a quick question regarding the correct syntax. I am trying to only load the jQuery file if the browser screen width is less than 1100px. <script type="text/javascript"> $(document).ready(function() { if ($(window).width() < 1100) { ...

I am encountering an issue where the key is not located in the response array in PHP, causing my JavaScript chart to remain

Hey there! I'm currently working on a school project and could really use some assistance. The task at hand involves creating a web interface that can interact with an endpoint in order to: - Authenticate a registered user to retrieve an authenticati ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

Iterating Through Array with Node JS Before Adding a New Property

There is a JSON input with data connected to a secondary model called Users. To process this, I need to iterate through listingData.Agents to extract the index ID and then use this ID to find the corresponding user. The challenge here is that due to asynch ...

Finding and removing the last portion of the innerHTML can be achieved by employing specific techniques

Looking to manipulate a <div> element that includes both HTML elements and text? You're in luck. I need to locate and remove either the last, nth-from-last, or nth plain text section within it. For example: <div id="foo"> < ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

Service in AngularJS designed specifically for storing and managing SEO metadata

I stumbled upon a tutorial that introduced me to using a service for dynamic SEO metadata here: However, I encountered an issue - It seems like the service is not accessible outside of the controller's view. <div ui-view></div> Here is t ...

Set the background image based on the attribute

I am facing a challenge with setting different background images to multiple divs. My approach involves using an attribute that contains the path to the specific image a div needs to utilize as its background. However, I'm encountering difficulties wh ...

Setting up a std::array within a function

Looking to develop a function that can resize a stack, I plan to create a new array with an increased or decreased size based on the value of max. Subsequently, the elements will be copied into this fresh array. void adjustSize(const int& max) { s ...

The interactive form fields are not functioning as intended due to a dynamic association issue

Issue with Adding Two Dynamic Form Fields Together I need to add two fields at once by clicking a single button, and each field should have a two-dimensional name structure like [0][0] and [0][1] for saving dual values Although I used jQuery to dyn ...

Utilize AngularJS to Capitalize the First Letter and the Letter Following a Dot (.)

I am seeking a solution to capitalize the first letter in a given string, like so: sumo => Sumo Additionally, I need to capitalize strings in the following format: Dr.ravi kumar => Dr.Ravi kumar Although I have implemented an Angular filter that ...

What is the process for accessing and utilizing the value returned by a promise in a separate file?

I have developed a small project to demonstrate an issue. There are a total of 5 files in this project: - A container file that includes all the dependency injections. - A service file containing the necessary functions to be executed. - A controller fil ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...

Revising the structure of a PHP array for seamless iteration in a Smarty template

I have been researching and struggling for days to resolve an issue involving adding a second Select query for distance calculations. The output I'm getting is fine, but it's not in a format that I can use with my existing script. To debug the pr ...

Strategies for resolving the java array index out of bounds error

In a client-server chat system, the server starts and clients connect to it. However, when a client tries to connect, it is successful but then encounters a lost connection condition in the array. catch (Exception ex) { out ...

Establish a global variable within the utils.js module in a Node.js environment

Hey there, I'm currently in the process of trying to figure out how to properly define a global variable in node.js. I am aware that it's not considered best practice, but in this specific scenario, it seems like the only way to go without involv ...

Ways to find the image source using JavaScript/Jquery upon page loading?

I've scoured countless forums, yet a viable solution still eludes me. My objective is simple - upon page load, I want to gather all elements with the ".home" class and store them in an array called arr. Subsequently, the script should iterate through ...

Why is the React Redux child component unable to access props?

Struggling with React and Redux? Here's the issue: A Component in my project is supposed to receive a value from Redux using mapStateToProps. The problem arises when trying to access this value within the child Component's renderFoo() function. ...