Ways to retrieve an item from a series of successive arrays

I'm struggling to find a solution to my current issue.

My goal is to retrieve the item at a specific index from a collection of separate arrays without merging them together.

Typically, to access the 3rd item in an array, you would use:

function getItemFromJustOneArray(index){
  var my_array = [1,2,3,4,5,6];
  return my_array[index];
}

getItemFromJustOneArray(2); // returns 3

However, my scenario involves multiple arrays that must remain separate and cannot be concatenated.

function getItemFromMultipleArrays(index){

  var array1 = [1,2];
  var array2 = [3,4,5];
  var array3 = [6];

  // I cannot use concat (or similar) to merge the arrays,
  // they need to stay separate
  // it could be any number of arrays, not just three

  // return 3;

}

getItemFromMultipleArrays(2); // SHOULD RETURN 3

I've attempted various methods using loops, but haven't been able to find a viable solution.

If anyone knows of an elegant approach to this problem, I'd greatly appreciate your input.

Answer №1

To consolidate all arrays within a new array, interweave them. Proceed to iterate over the new array, decreasing the index by the length of each array until it aligns with the size of the current element. Subsequently, you can retrieve the corresponding element from the nested array.

function getItemFromMultipleArrays(index) {

  var array1 = [9, 10];
  var array2 = [11, 12, 13];
  var array3 = [14];
  var all_arrays = [array1, array2, array3];
  var i;
  for (i = 0; i < all_arrays.length && index >= all_arrays[i].length; i++) {
    index -= all_arrays[i].length;
  }
  if (i < all_arrays.length) {
    return all_arrays[i][index];
  }
}

console.log(getItemFromMultipleArrays(1)); // EXPECTED OUTPUT: 12

Answer №2

Why not combine multiple arrays into one and use the index to access the value?

function getItemFromMultipleArrays(index) {
    const
        array1 = [1, 2],
        array2 = [3, 4, 5],
        array3 = [6];

    return [...array1, ...array2, ...array3][index];
}

console.log(getItemFromMultipleArrays(2)); // 3

Another method is to use an offset when iterating through arrays.

function getItemFromMultipleArrays(index) {
    const
        array1 = [1, 2],
        array2 = [3, 4, 5],
        array3 = [6],
        temp = [array1, array2, array3];

    let j = 0;

    while (index >= temp[j].length) index -= temp[j++].length;

    return temp[j][index];
}

console.log(getItemFromMultipleArrays(2)); // 3
console.log(getItemFromMultipleArrays(5)); // 6

Answer №3

By combining all the arrays into one large array, we can easily access elements without altering the original arrays. Below is a snippet of code that demonstrates this concept:

// This function takes multiple arrays as arguments and returns a new concatenated array.
function connectArrays(...arrays) {
  return [...arrays.flat()];
}

// Function to retrieve an item from multiple arrays at a specified index.
function getItemFromMultipleArrays(index) {
  var array1 = [1, 2];
  var array2 = [3, 4, 5];
  var array3 = [6];
  var allArrays = connectArrays(array1, array2, array3);
  
  return allArrays[index];
}

getItemFromMultipleArrays(2); // This should return 3

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

Updating the NPM entry point without relying on an index.js file

After successfully publishing a private module to NPM, which contains shared code used by multiple services, I encountered an issue with the transpilation process. Since the code is written in ES6, it needs to be transpiled using Babel before being publish ...

Store the output of JavaScript in a PHP variable

My objective is to convert any image to base 64 and then store the converted string in a PHP variable before inserting it into my database. JavaScript Code: function uploadFile() { if (this.files && this.files[0]) { var FR= new FileReader ...

Dependable Timeout Functionality in JavaScript

We are currently developing an AngularJS application that presents users with questions and keeps track of the number of correct answers within a strict 20-minute time limit. However, there are some challenging requirements we need to consider: Accuracy C ...

Simple steps to add a click event listener to every element within a div

I need to assign a click handler to multiple elements and perform different actions based on which one is clicked. To illustrate, I can create an alert displaying the class of the button that was clicked. The elements I am working with have a similar str ...

When attempting to retrieve the innerHTML of a <div> element within a <Script> tag, the value returned is undefined

Utilizing a masterpage to create a consistent header across all content pages, I encountered an issue on one page. I needed to retrieve the innerHTML of a div element and pass it to an input control on the same page in order to access the updated innerHTML ...

Challenges encountered while working with OpenWeather API

I created a weather prediction web application using p5.js. It functions perfectly on my local server. However, I keep encountering this issue on the GitHub page: Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure ...

Has anyone else encountered the issue where the JavaScript for Bootstrap version 4.3.1 is malfunctioning on Firefox version 65.0.1?

While browsing through the bootstrap v 4.3.1 documentation on firefox v 65.0.1, I noticed an issue with the javascript not functioning properly. For instance, the carousel component is not progressing to the next slide with its transition animation as it s ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...

Issue with Auth0 not properly redirecting to the designated URL in a React application

auth.js import auth0 from 'auth0-js'; export default class Auth { constructor() { this.auth0 = new auth0.WebAuth({ domain: '<properURL>', clientID: '<properID>', re ...

Populating options in <select> for Internet Explorer version 5

Let me address the first question here. The reason why I am using IE5 is because I am working on a Windows CE device which limits me to this browser. My application involves a webpage with various elements. In my HTML code, I have two text fields and a se ...

How can I make the row color of a jQuery datatable change when the row is selected?

One of my challenges involves implementing a jquery dataTable (view here) where each row contains a checkbox. I want the row's color to change when the checkbox is checked. This is the approach I attempted: <table id="tabellaOrdinaFarmaci" class=" ...

Refreshing a page following an AJAX request made with jQuery

I am working on a JSP page that shows student details. When a student is selected from the dropdown box, it triggers an onchange event to retrieve the minimum and maximum marks for that student. <form name="listBean"> <c:forEach var="Item" i ...

Invoke a JavaScript function from a dynamically inserted nested function

My primary application loads JavaScript files based on the page being visited: var MainApp = (function() { function loadPage(folder, template) { $.getScript('scripts/' + template + '.js') .done(function() { ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

The ng-disabled directive is functioning properly, however it is not having any impact on the disabled attribute in

Having an issue with enabling or disabling a button based on the selection of a certain string from a dropdown menu. HTML <select ng-change="checkType()" ng-options="sth in sth for things"></select> <input ng-disabled="{{toggleDisable}}" ...

React Native can trigger a press event, as long as it is not within

My situation involves triggering an action when clicking on the parent component (TouchableOpacity, for example), but not triggering anything when clicking on the children components (Screen and others). It's similar to preventing bubbling on the web. ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Flag is activated to retrieve the data from the @Input source

@Input() config= []; flag = false; I need to change the flag to true only when I receive data in the config from the @input. Where should I do this? The data in the config is delayed and I am unable to access it in ngOnInit but can get it in ngOnChanges. ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below https://i.sstatic.net/qUFP6.png This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, ...