P5: Exploring the Intersection of Arrays

I am faced with the challenge of extracting values from one array based on indices from another array. I have successfully loaded two text files using loadStrings and stored the data in two separate arrays. The lengths of the two text files are different - the first file includes three values per line: a line number, an x coordinate, and a y coordinate. The second file contains the line numbers from the first file for which I need to extract data. With only two months of coding experience, I find this task daunting and it has left me stuck! Below is the code I have managed to write so far:

let data1;
let data2;
let parsedData1;
let parsedData2;
let combinedData;

function preload() {
  data1 = loadStrings('assets/data1.txt'); // load the data1 file
  data2 = loadStrings('assets/data2.txt'); // load the data2 file
  // console.log(data1);
  // console.log(data2);
}

function setup() {
  createCanvas(600, 400);   
}

function draw() {
  noLoop();
  background(0);
  
  readData1()
  readData2()
}

function readData1() {
  parsedData1 = new Array(data1.length); // create an array for the parsed data

  for (let i = 0; i < data1.length; i++) {
    let parsedData1 = splitTokens(data1[i]);
    // console.log(data1); 
  }
}

function readData2() {
  let combinedData = concat(parsedData1, data2);
  // console.log(combinedData);
}

The text files I have loaded contain the following information:

text1:

1 200 50
2 100 25
3 200 63
4 123 456
5 124 200
6 700 500
7 600 500
8 200 121
9 300 100

text2:

3
5
8

The desired result I am aiming for is:

3 150 100
5 124 200
8 200 121

I have been advised that loops can help achieve the desired result, but I am still working on figuring out how!

Answer №1

When it comes to dealing with loops, here's a method utilizing loops:

In cases where the "index numbers" in data1.txt are continuous:

for(let i = 0; i < data2.length; i++) {
  let index = data2[i];
  console.log(data1[index]);
}

If the index numbers are not continuous, you can opt for nested loops like this:

for(let i = 0; i < data2.length; i++) {
  let index = data2[i];
  for(let j = 0; j < data1.length; j++)
  {
    let line = data1[j];
    let lineArr = line.split(" ");
    if(lineArr[0] == index) {
      console.log(line);
    }
  }
}

Answer №2

If you want to compare two strings, you'll need to format them into arrays or a similar data structure.

Take a look at this code snippet:

  let text1 = document.getElementById("originaltext").innerHTML.trimRight();
  let compare1 = document.getElementById("comparevalues").innerHTML.trimRight();
  let a1 = text1.split("\n");
  console.log(a1);
  let c1 = compare1.split("\n");
  console.log(c1);
  const r1 = a1.filter(a => c1.includes(a.split(" ")[0]));
  console.log(r1);
<pre id="originaltext">
1 200 50
2 100 25
3 200 63
4 123 456
5 124 200
6 700 500
7 600 500
8 200 121
9 300 100
</pre>
<pre id="comparevalues">
3
5
8
</pre>

This code snippet extracts strings from PRE tags (in this case, it would be from your original text) and transforms them into arrays. It then uses the "includes" method to filter the first array based on whether the first number appears in the second array, creating a new array with the results.

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

Each time I invoke the setInterval function, my counter speeds up - using vuejs

In my development process, I am creating a countdown that is triggered by a function. The main objective is to reset the countdown each time a user answers a question in the game and a new question appears. However, I have encountered a challenge where i ...

Managing a collection of input values

Is there a way to effectively manage an array of input fields using reactjs? Take for instance this text field: <input type="text" value="" name="test[]" /> Below is the code I'm currently working with: render () { ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

Is it possible to utilize the glob method for refining a current collection of file paths?

Currently, I am utilizing glob to conduct file search operations in Node, along with glob patterns for an "ignore" list. However, my goal is to utilize only the ignore list to filter a current list of files (specifically changed files from git). Is there ...

Press the button using Selenium WebDriver with Java

Currently, I am utilizing Selenium Webdriver for Chrome and Firefox along with Java. After performing various actions, I stumbled upon a typical source code snippet like this: <input type="button" value="yoyo" class="btn" onClick="SubmitForm(this, &ap ...

Unlocking Secret Data with External JavaScript

Currently, I am focusing on validating user input, specifically the name to ensure it is at least 6 characters long. Although I plan to implement more validation, I am facing an issue with error display. When the JavaScript code is embedded within the HTML ...

Prevent reloading the page when adding a flash element using JavaScript (jQuery)

Here is the function I am working with: function onVideo(vchat, idUser){ $('#videollamada').html('<div class="videollamada">'+ '<div align="right">'+ ...

Having issues with the functionality of the jQuery HTML function

I'm working on this jQuery code snippet: $('#wrapper').html('<img src="/loading.gif">'); var formdata = $("#validateuserform").serialize(); $.post("/userformdata.php",formdata,function(html){ if(html) ...

Displaying elements of an array in a textView in Swift

Is there a way to incorporate all the items from an array into a textView with a slight time delay of 1 second? Using the swift programming language. (I am still in the early stages of learning programming) ...

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

What is the best way to organize a collection of tuples based on an Integer value?

I am seeking guidance on how to sort an array of tuples where each tuple consists of a name and an age value. The array looks something like this: var array = [("John Doe", 13), ("The Guy", 15), ("The Person", 19)] My goal is to rearrange the array in d ...

Converting Microsoft Word files into HTML format

Similar Question: Converting .doc to html using PHP I'm looking for a way to transform a word document into HTML format for embedding on a webpage. I'd like to accomplish this task using PHP. Any suggestions on how to achieve this? ...

Why am I encountering issues accessing a child property in TypeScript?

Here is some TypeScript code that I am working with: export interface SelectQuery_thing { __typename: "ThingQueryPayload"; content: (SelectQuery_thing_content | null)[]; pageInfo: SelectQuery_thing_pageInfo; } export interface SelectQuery_thing_con ...

Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. ...

What is the best way to deactivate a button when a certain input field is left blank?

I'm having trouble figuring out how to deactivate a button when specific input fields are empty, while others can remain optional for the process. In my course, we were taught to disable the button until all inputs are valid, so I'm a bit confus ...

Tips for transferring data and events between named views within Vue Router

I have a layout structured like this: .------------------------+----------------. | Current Tab Title | Controls | +------------------------+----------------+ | Tab1 Tab2 [Tab3] | +---------------------------------------- ...

The process of transmitting messages back and forth between a popup script and a content script

I am in the process of developing a Chrome extension that involves sending data requests from a popup script to a content script (via a background script), analyzing the request on the content script, and then sending back a response (again through the bac ...

The functionality to refresh an input field upon clicking a button is not functioning as expected

I am currently developing a small MVC.NET web application with user input functionality. The goal is to calculate and display the results in two input fields upon button click. However, I am facing an issue where the input fields remain empty after the but ...

What is the recommended value for the auto-incremented ID field when using the POST method in Node.js?

Currently, I am utilizing the mysql package for NodeJs in order to Post Data to a MySqlDB. Below is an example of my code: app.post('/countries', (req, res) => { const country = req.body.country; const city = req.body.city; const t ...