Iterate through a JavaScript grid and display the items

I am attempting to iterate through a JavaScript table, aiming to display the elements located between two selections made by the user.

Here is an example of the table structure: if the user selects IDs 2 and 5, the loop should display rows 3 and 4. I tried using a for-loop but did not achieve the desired outcome.

var station = [
  [0, 'JAMAA EL FNA', 'L1'],
  [1, 'KOUTOUBIA', 'L1'],
  [2, 'HOTEL DE VILLE', 'L1'],
  [3, 'R.P BERDII', 'L1'],
  [4, 'GRAND POSTE', 'L1'],
  [5, 'CAREE EDEN', 'L1'],
  [6, 'PL ABDELMOUMEN', 'L1'],
  [7, 'PLACE D ARMES', 'L1'],
  [8, 'FST', 'L1'],
  [9, 'SEMIRAMIS', 'L1'],
  [10, 'DR KUDIA', 'L1'],
  [11, 'MCDO', 'L1'],
  [12, 'CAFE AMINE', 'L1'],
  [13, 'FAC SEMLALIA', 'L1'],
  [14, 'ROUIDATE', 'L1'],
  [15, 'CLUB MINISTRE JUSTICE', 'L1'],
  [16, 'BEN TBIB', 'L1'],
  [17, 'ASWAK SALAM', 'L1'],
  [18, 'BAB DOUKALA', 'L1'],
  [19, 'JAMAA EL FNA', 'L2'],
  [20, 'KOUTOUBIA', 'L2']
];

Answer №1

To filter and select specific items, you can use the following code:

let selectedItems = station.filter(curr => curr[0] > startNum && curr[0] < endNum)

var station = [
  [0, 'JAMAA EL FNA', 'L1'],
  [1, 'KOUTOUBIA', 'L1'],
  [2, 'HOTEL DE VILLE', 'L1'],
  [3, 'R.P BERDII', 'L1'],
  [4, 'GRAND POSTE', 'L1'],
  [5, 'CAREE EDEN', 'L1'],
  [6, 'PL ABDELMOUMEN', 'L1'],
  [7, 'PLACE D ARMES', 'L1'],
  [8, 'FST', 'L1'],
  [9, 'SEMIRAMIS', 'L1'],
  [10, 'DR KUDIA', 'L1'],
  [11, 'MCDO', 'L1'],
  [12, 'CAFE AMINE', 'L1'],
  [13, 'FAC SEMLALIA', 'L1'],
  [14, 'ROUIDATE', 'L1'],
  [15, 'CLUB MINISTRE JUSTICE', 'L1'],
  [16, 'BEN TBIB', 'L1'],
  [17, 'ASWAK SALAM', 'L1'],
  [18, 'BAB DOUKALA', 'L1'],
  [19, 'JAMAA EL FNA', 'L2'],
  [20, 'KOUTOUBIA', 'L2']
];

const start = document.getElementById('start')
const end = document.getElementById('end')
const results = document.getElementById('results')

function updateSelection() {
  let startNum = parseInt(start.value || -1)
  let endNum = parseInt(end.value || station.length + 1)
  let selectedItems = station.filter(curr => curr[0] > startNum && curr[0] < endNum)
  results.innerHTML = selectedItems.map(item => `<tr><td>${item[0]}</td><td>${item[1]}</td><td>${item[2]}</td></tr>`).join('')
}

updateSelection()
start.addEventListener('input', updateSelection)
end.addEventListener('input', updateSelection)
table {
  width: 100%;
}

table th {
  text-align: left;
}
Start: <input id="start" type="number"> End: <input id="end" type="number">

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Col 1</th>
      <th>Col 2</th>
    </tr>
  </thead>
  <tbody id="results"></tbody>
</table>

Answer №2

It seems like you are interested in refining your collection of stations

let minimumValue = 2;
let maximumValue = 5;
let filteredStations = stations.filter( item => item[0] > minimumValue && item[0] < maximumValue);

The variable filteredStations will now hold the data with the first column values between 3 and 4.

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

Unusual Behavior Uncovered in jQuery Selectors

Have you ever noticed a peculiar behavior of jQuery selectors? I recently discovered that when the page contains elements with non-unique IDs, jQuery returns different results for the same selectors: Here's an example of HTML code: <button id=&ap ...

What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, espe ...

Execute a JavaScript code prior to sending a response directly from the ASP.NET code behind

On my .aspx page, I have the following code which prevents the page from responding without confirmation: <script type="text/javascript"> window.onbeforeunload = confirmExit; function confirmExit() { return 'Are you sure you wan ...

Tips for successfully importing .eot and .woff documents using Babel?

When attempting to start my project, I encountered the following error message (You may need an appropriate loader to handle this file type.) for .eot, .woff, .ttf, and .svg files: ERROR in ./src/styles/fonts/nm/icons/nm-icons.svg?aaf8685e87a6901c76c52d00 ...

Navigating programmatically to another page in Next.js can be easily achieved by utilizing the useRouter hook

Following a post request to an external API, my goal is to navigate back to the homepage. While I am familiar with React, this is my first experience using Next.js. Here's the snippet of code: export default function New({genres}) { const createMovie ...

contrasting module export approaches

Let me clarify that my query does not revolve around the disparity between module.exports and exports. Instead, I am interested in understanding the contrast between exporting a function that generates an object containing the functions to be shared upon i ...

Unable to locate the module '/workspace/mySQL/node_modules/faker/index.js'

Hi there, I'm currently facing an issue while trying to run the app.js file in my project through the terminal. It keeps showing me an error message that I am unable to resolve. To provide some context, I have already installed the faker package using ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

Click the button on your mobile device to open the already installed Android app

After creating a small Android app using jQuery Mobile, I incorporated a button to open another native Android app. Is it feasible for the jQuery Mobile app button to load/open an already installed and functioning native Android app upon click? I would gr ...

Is it possible to preserve the <canvas> elements to use for future animation frames?

Currently, I am working on a graph visualization project that involves complex calculations being done on an HTML5 canvas. My goal is to create an interactive animation where the graph remains fixed, but additional elements are overlaid as the mouse moves ...

What is the best way to conceal selected options in a MUI multiselect in the select field?

I'm currently working with a MUI multiselect feature to allow for the selection of multiple options from a dropdown menu. However, I am facing an issue where I do not want the selected options to be visible within the dropdown field. Is there a way to ...

Generate a fresh JSON object by adjusting JSON data in Angular 6

Here is a sample JSON structure: [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx" } }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx" } ] I need to split the values of the K ...

Should the method of creating a Dropdown with Angular be considered a poor practice?

I've recently dived into Angular and successfully created my first dropdown using it, which is working great. However, I'm a bit concerned about the number of comparisons being made and wondering if this approach is considered bad practice. The ...

Tips on handling a Vue computed property

I am struggling to dispatch an object that is created within a computed property in vue.js. Being fairly new to this framework, I can't seem to make it work. My goal is to dispatch the object named "updateObject" to the vuex-store. I have tried using ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

Retrieve Files with Angular Framework

I'm looking to implement a file download or view button using Angular without making a call to the backend. The file is static and the same for all users, so I want to avoid unnecessary server requests. Many solutions involve using the "download" att ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Display a dialog box in jQuery UI 1.7 autocomplete when an item is selected

After implementing an autocomplete widget, I noticed that a dialog appears when an item is selected. However, I am struggling to get a specific field in the dialog to receive focus upon opening. Here is what I have attempted so far: //HTML <form actio ...

``Are you looking to create multiple canvases in a loop?

I've managed to get this command working exactly as I wanted: http://jsfiddle.net/m1erickson/64BHx/ However, I didn't anticipate how challenging it would be to turn the drawing into reality here: What I attempted to do is illustrated in this li ...