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

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Using Node.js to send a photo through a Telegram Bot

I've been trying to send a photo via node.js using this function, but it's not working. telegram-bot-api https://www.npmjs.com/package/telegram-bot-api var telegram = require('telegram-bot-api'); var api = new telegram({ token: & ...

Is the parent node of the input element the input element itself?

When working with a DOM object obj of type <input>, I encountered an issue where attempting to obtain its parent node using obj.parentNode resulted in the same obj being returned. Is this behavior specific to <input> objects? What other types o ...

"Encountering issues with Node.js while loading required modules

Having created an API utilizing hummus.js, I encountered a problem after uploading it to my server (Ubuntu Root + Plesk Onyx) and performing an npm install on my package.json. Despite receiving a "Success" status message during the installation process, my ...

Utilize SectionList and a custom header view on Y to achieve a translation effect that creates a visually appealing empty space as

Hello everyone, I am fairly new to React Native and the Animated API. My goal is to create a simple parallax header and an Animated SectionList similar to this demonstration. https://i.stack.imgur.com/R2GBP.gif Below is a snippet of my code: export defa ...

Unable to locate the <router-view> component within VueRouter

I recently completed a project using Vue.js 3.2.13 and Vue-Router 4.0.14. Despite my efforts to ensure everything was set up correctly, I encountered an error in the browser that said "[Vue warn]: Failed to resolve component: router-view". The specific lin ...

Clicking 'Submit' triggers a continuous loop upon loading

I set up this form to automatically submit once the page has finished loading. However, I seem to be encountering a problem where the page gets stuck in a continuous loop of reloading. HTML <body onload="document.getElementById('filters').su ...

What steps should be taken to switch a class from one li element to another and remove it in the process?

As I develop the navigation bar for my website, I am faced with a challenge. I want to create a button-like behavior where clicking on an li element triggers a drop-down section underneath it without using the # attribute to prevent jumping to the top of t ...

Guide on incorporating JSON information into an HTML table

Currently, I am retrieving data that needs to be added to an HTML table once it is received. I have attempted some methods, but I am unable to dynamically add the data after the page has loaded. I aim to accomplish this using either JavaScript or jQuery. ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Dynamically Insert a Row into a Table using Bootstrap and JavaScript

Can someone provide assistance with my code? Specifically, I am looking to add the index number whenever a user clicks the add button and would like to know how to insert text input similar to the first row. I am currently in the process of learning JavaSc ...

Display the JSON object when making requests to the Instagram API

I'm currently working with the instagram API and have successfully displayed images and their URLs on the screen. However, I'm wondering if there's a way to print the JSON object on the screen so I can understand how to access the different ...

Solving complex promises in both serial and parallel fashion

My current function performs four tasks that must be executed in a specific sequence: - promise1 - promiseAfter1 // In parallel - promise2 - promiseAfter2 To ensure the promises are handled sequentially, I have structured two separate functions as follows ...

How can I use Ajax to show only one div on the entire page while keeping the CSS and other header content intact

One of my clients is looking to integrate a merch shop into their website. The existing merch page is not visually appealing and doesn't match the aesthetic of the client's site. I am considering using AJAX GET to fetch the content of the merch p ...

In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Belo ...

The Node function will yield a BluebirdJS Promise

I've encountered a minor issue with this script. While it functions properly, the "runTenant" method is not returning a promise that needs to be resolved with "all()". Here's the code snippet in question: Promise.resolve(runTenant(latest)).then ...

Object.assign changes the original array object in place

I am facing a challenge while attempting to modify the value of a specific index in my state, specifically the property post_comments. The issue lies in the fact that even though I am only modifying a copy of the state, the actual state is also being alter ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Would you suggest using angularjs for authentication in large-scale applications?

As I continue to learn and utilize the AngularJS framework, I have noticed that while some of its features are impressive, some key aspects make it challenging for authentication-based applications. For example, let's consider a scenario where a webs ...

When attempting to submit information to a database table, I encounter an error in the browser console: "Uncaught (in promise) Error: Request failed with status code 404."

In my React Node project's login page, I am encountering the following issue. Despite thoroughly reviewing my code after each execution, the error persists. My goal is to pass data from the login page into my MySQL database; this marks the initial sta ...