Obtain values from a specific set, and then filter out values from an array that correspond to the index of that set into distinct arrays

The Problem I'm Facing

Currently, I am dealing with a large data table that contains a mix of relevant and irrelevant data. My goal is to filter out the information I care about and display it in a more concise table. Using RegEx, I have managed to identify the indexes of the desired data and store them in a set. Here's a snippet of my approach:

Importing and Processing Excel Data

onFileChange(event: any) 
  {
    const inputFile: DataTransfer = <DataTransfer>(event.target); 
    const fileReader: FileReader = new FileReader();
    fileReader.onload = (event: any) => 
    {
      const binaryString: string = event.target.result;
      const workBook: XLSX.WorkBook = XLSX.read(binaryString, { type: 'binary', sheetStubs: true}); 

      const workSheetName: string = workBook.SheetNames[0];
      const workSheet: XLSX.WorkSheet = workBook.Sheets[workSheetName];

      this.data = <Array>(XLSX.utils.sheet_to_json(workSheet, 
      {header: 1, blankrows: true })); 
    };
    fileReader.readAsBinaryString(inputFile.files[0]);  
  }

Essentially, this function reads an Excel sheet and converts it into an array object, where each array represents a row in the sheet. To further filter the data, I implemented the following function:

columnsWithManufacturer()
  {
    var someManufacturers = [//list of regex phrases//];
    var manColumnIndexes = new Set();

    for (var manufacturer of someManufacturers)
    {
      for (const row of this.data)
      {
        for (var cell=0; cell< row.length; cell++)
        {
          if (manufacturer.test(row[cell]))
          {
            manColumnIndexes.add(cell)
          }
        }
      }
    }
    return manColumnIndexes
  }

Here, 'cell' represents the column value in the Excel sheet where the data is located, and the set 'manColumnIndexes' holds unique column numbers where relevant data is found. My objective now is to segregate this data into separate arrays based on the column numbers. For example, data from columns 14, 16, and 17 should be stored in separate arrays using a distinct function.

My Approach and its Flaw

In an attempt to achieve this, I created a new function as follows:

pushIntoSeparateArrays()
  {
    var manufacturersArrays = [this.primaryManufactArray,this.altManufactArr,this.altManufactArr2,this.altManufactArr3]

    var manufactIndexes = this.columnsWithManufacturer()

    for (var array of manufacturersArrays)
    {
      for (var row in this.data)
      {
        manufactIndexes.forEach((value) =>
        {
          array.push(this.data[row][Number(value)])
        })
      }
    } 
  }

However, as I've realized, this approach ends up pushing all the data from all column values into all arrays. There seems to be a missing step in my process. Can you assist me in properly separating the data into distinct arrays as intended?

Answer №1

It seems like the issue lies in the repetition of the same operation for each element in the manufacturersArrays without any conditional check.

A more efficient approach would be to create a map that stores the columns of interest along with their respective arrays. Take a look at the example below:

const data = [
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
];

function columnsWithManufacturer() {
  return new Set([0, 1, 4]);
}

function pushIntoSeparateArrays() {
  const columns = columnsWithManufacturer();
  const interestingColumns = new Map();
  
  columns.forEach(column => {
    const array = [];
    interestingColumns.set(column, array);

    data.forEach(row => {
      const cellValue = row[column];
      array.push(cellValue);
    });
  });
  
  return interestingColumns;
}

const interestingColumns = pushIntoSeparateArrays();
console.log(Array.from(interestingColumns.get(0)));
console.log(Array.from(interestingColumns.get(1)));
console.log(Array.from(interestingColumns.get(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

After retrieving a value from attr(), the object does not have the 'split' method available

I need to implement the split method on a variable fetched using attr. This is the code snippet I am attempting: $(document).ready(function() { $('.some_divs').each(function() { var id = $(this).attr('id'); var ida = ...

Looping through a PHP array and converting it into an SQL string using the

Let's start fresh. We begin with three tables: Transaction Table: meter_id | bay_number | trans_date_time | amount ----------+------------+----------------------------+-------- 1078 | 5 | 2013-06-03 09:59:32+10 | 5.0 ...

What is the method for calling a JavaScript function from one file to another within a Node.js environment?

Just starting out with JavaScript and exploring the idea of breaking the code into multiple modules. While working with nodejs, I've encountered an issue where it's complaining about pathChecker not being defined. Any insights on how to resolve t ...

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...

What is the best way to create a JavaScript "input" field that only accepts vowel letters?

Is there a way to create an "input" field that only accepts vowel letters? Additionally, I want to ensure that copying and dragging text into the input field will also be filtered out. <div class="field"> <input class="fie ...

Generate a D3.js vertical timeline covering the period from January 1, 2015 to December 31, 2015

I am in need of assistance with creating a vertical timeline using D3.js that spans from the beginning of January 2015 to the end of December 2015. My goal is to have two entries, represented by colored circles, at specific dates within the middle of the t ...

Transforming JSON data into a dynamic Tableview

I've been experimenting with this issue for quite some time now, but I can't seem to find a solution. My API returns tasks in JSON format. When I print the data using Ti.API.info(this.responseText), it looks like this: [INFO] [{"created_at":"20 ...

Spirit.py navigates using javascript

Having trouble with Ghost.py. The website I'm trying to crawl uses javascript for paginated links instead of direct hrefs. When I click on the links, selectors are the same on each page so Ghost doesn't wait since the selector is already present. ...

Learn the process of incorporating a plugin into a React JS project

As a ReactJs beginner, I am encountering an issue while trying to import a new plugin in my react app. I am currently working on React without using node or npm as shown below. <!-- some HTML --> <script src="https://unpkg.com/babel-standalone@6 ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

Updating an Angular 2 project for the MEAN Stack development platform

A few weeks back, I embarked on an Angular2 project by following the "Tour of Heroes" tutorial. As I progressed, my project grew in complexity with routers, rest services, and hundreds of lines of code. Now, as I look to transition my project to the MEAN ...

What is the process for converting the color names from Vuetify's material design into hexadecimal values within a Vue component?

I'm looking to obtain a Vuetify material design color in hexadecimal format for my Vue component's template. I want to use it in a way that allows me to dynamically apply the color as a border, like this: <div :style="`border: 5px solid $ ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Modify a JavaScript object in JSON format using another object as reference

Consider two JSON formatted JavaScript objects: obj1 = { prop1: 1, prop2: 2, prop3: 3 } obj2 = { prop1: 1, prop2: 3 } In the context of jQuery or Angular, what is the recommended practice to update obj2 into obj1 while also re ...

Updating React props using useState?

Below is a component that aims to enable users to update the opening times of a store. The original opening times are passed as a prop, and state is created using these props for initial state. The goal is to use the new state for submitting changes, while ...

Accessing Elasticsearch from Kibana without the need for authentication and sending requests freely

Currently, I am in the process of developing a plugin for Kibana with the intention of establishing communication with Elasticsearch, utilizing Shield for security measures. Thus far, my approach has involved sending requests through the server with code ...

Using a variable as a URL parameter in a jQuery ajax request: tips and tricks

$.ajax({ type:"POST", url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table, contentType: "application/json; charset=utf-8", crossDomain:true, dataType:'jsonp', succe ...

Developing a single page that caters to various users' needs

Greetings to all my friends, As a front end developer, I am in the process of implementing a dashboard for a project that involves different users with varying permissions. Each user should only have access to certain parts of the page, resulting in some ...