Consider pushing items onto an array only once when the condition is met, instead of adding to the array every

I have been tasked with importing Excel files containing customer orders into my web application. The process involves converting the data in the file into an object of arrays, where each array represents a row from the Excel sheet.

Once the data is imported, I need to search for specific items within a column to identify the shoe brands requested by customers. However, I encountered an issue where the same column data was being pushed into the array multiple times instead of just once.

In the code snippet below, you can see how I attempted to address this problem using conditional statements:


for (let i = 0; i < this.data.length; i++) {
    if (this.data[i].indexOf('Adidas') !== -1) {
        let brandIndex = this.data[i].indexOf('Adidas');
        for (let j = 0; j < this.data.length; j++) {
            this.brandArray.push(this.data[j][brandIndex]);
        }
    } else if (this.data[i].indexOf('Puma') !== -1) {
        let brandIndex = this.data[i].indexOf('Puma');
        for (let j = 0; j < this.data.length; j++) {
            this.brandArray.push(this.data[j][brandIndex]);
        }
    } else if (this.data[i].indexOf('Nike') !== -1) {
        let brandIndex = this.data[i].indexOf('Nike');
        for (let j = 0; j < this.data.length; j++) {
            this.brandArray.push(this.data[j][brandIndex]);
        }
    }
}

The current implementation pushes the column data into the array every time a condition is met. Is there a more efficient way, possibly utilizing the '%' operator or another function, to ensure that each column is only added to the array once?

If, for example, I had a customer sheet with the following entries:

https://i.stack.imgur.com/G62py.png

I would like the resulting array to be

[Nike, Adidas, Puma, Puma, Asics, Nike]

Answer №1

If you want to efficiently add unique elements without checking if they already exist in an array, consider using a Set data structure. By adding elements to a Set and then converting it back to an array, you can avoid the potential O(n²) time complexity that may arise from repeatedly checking for duplicates in an array.

Here is an example of how you can use a Set:

const mySet = new Set();

mySet.add(123);
console.log([...mySet]);

mySet.add("hello world");
console.log([...mySet]);

mySet.add(123);
console.log([...mySet]);

To convert a Set back to an array, you can use either [...mySet] or Array.from(mySet).

In your code snippet, you are initializing a Set called manufactSet and populating it with unique values. After processing the data, you convert the Set back to an array named manufactArray.

However, there seems to be confusion in the loop logic where you push all elements when encountering a specific value ('Adidas'). It might be more appropriate to push only that specific element rather than the entire row. Consider revising this section of your code accordingly.

Based on your requirements, it appears that you want to extract specific manufacturers multiple times from different rows. In this case, utilizing a Set may not be suitable. Here's an optimized version of your code in ES6:

const someManufacturers = new Set(['Adidas', 'Puma', 'Nike']);

function getColumnNumber() {
  for (const row of this.data) {
    for (let i = 0; i < row.length; i++) {
      if (someManufacturers.has(row[i])) return i;
    }
  }
}
var manufacturerColumnNumber = getColumnNumber();

for (const row of this.data) {
  this.manufactArray.push(row[manufacturerColumnNumber]);
}

By adjusting your implementation as suggested above, you can achieve the desired functionality more efficiently while avoiding unnecessary iterations through the data.

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

Locate the class ID and refine the search results by another class

I am currently working on a task that involves extracting the first <li> element's id where it has the class name my_class, and checking if the <span> with the class Time contains a ":" using jquery. Below is the sample HTML structure: & ...

What is the best way to save the output of an asynchronous (AJAX) function in a variable?

This isn't a repeat query. I'm seeking assistance in locating a technical solution that hasn't been covered in the post How do I return the response from an asynchronous call? If .then() doesn't resolve the Promise, how can I pinpoint ...

React - Incorrect components experiencing style changes due to setTimeout

Check out the code snippet here: https://jsfiddle.net/69z2wepo/204131/ A main component displays two 'notifications' each with different disappearance timings. class Page extends React.Component { constructor(props) { super(props); t ...

Vue3 and Ionic combined to create a Component that became a reactive object in Vue

Vue is issuing a warning about receiving a Component as a reactive object, which can cause unnecessary performance overhead. The warning suggests using markRaw or shallowRef instead of ref to avoid this issue. However, in my code, I am not explicitly using ...

Is there a method to iterate through an HTML quiz in order to extract text from "label for" with the value of "true"?

I need assistance with extracting all the correct answers from a multiple choice radio button quiz. The correct answers are identified by the attribute value="true" in the HTML code. Is there a way to iterate through and retrieve the text of all the corr ...

Rotating an input 90 degrees within a div for unique positioning

I used JavaScript to make an input range vertical, like so: var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)" ...

What is the optimal approach to organizing components' props?

As I dive into testing Material-UI components, one thing has me puzzled. Take the List component for example - why use such syntax? <List component="nav"> <ListItem button selected={selectedIndex === 0} onClick={(event) => ha ...

Tips for choosing Week Range values with Selenium WebDriver

Currently, I am working with Selenium WebDriver and I am trying to figure out how to select week range values from a dropdown menu at once. I have a dropdown called Period, which, when selected, automatically reveals additional dropdowns for From week and ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

What is the best way to implement multiple ternary operators within HTML code?

Consider the following code snippet: It currently applies CSS classes up to red4, but I want to apply CSS classes up to red11. Additionally, the variable "size" in myData should be dynamic. For example, size could range from 0-20 // 0-100 // 0-10000, etc., ...

Troubles with configuring the Express server in relation to the public directory

After creating two separate bundles for my server and client, I encountered an issue where the client bundle is not being downloaded by the browser when accessing the root route. To address this, I instructed Express to treat the public/ folder as a freel ...

ACL - Utilize ACL in conjunction with the passport authentication system

I am experimenting with node_acl in combination with passport-local. Unfortunately, I am facing an issue when trying to secure the route for the admin-user '/admin', as it keeps redirecting me to the /login page. Below is a simplified version of ...

Prevent the Stop Function from being executed repeatedly while scrolling

I have implemented infinite scrolling in my react/redux app. As the user nears the bottom of the page, more contents are loaded dynamically. However, a challenge arises when the user scrolls too fast and triggers the function responsible for fetching cont ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

Creating a JavaScript-powered multi-department form: A step-by-step guide

Is there a way to maintain the form displayed on a webpage created in HTML5 and JavaScript for logging calls across three different departments? With buttons assigned to each department, clicking on them reveals the respective HTML form. That said, every t ...

In what format is the parameter accepted by the .getDay() method?

Here's the plan: I need to extract information from an input element with type set as date. This data will then be stored in a .json file and later parsed when the program is initiated. Subsequently, I aim to utilize the date.getDay() function to dete ...

How can you show in an array only the elements that meet a filter condition in a MongoDB query?

Below is a list of objects: [ { field0: value0, field1: value1, field2: { field3: value3, field4 : [ { sfield1: svalue110, sfield2: svalue210 }, { sfield1: svalue111, sfiel ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

Embedding a stylesheet into an HTML document can be done automatically

Currently, I am working on creating standalone error pages (404/503) as individual HTML files. My server-side setup involves Node.js, but these specific files will be hosted directly in Nginx. One of the challenges I am facing is automatically including a ...

Troubleshooting: Issue with incorporating libraries into my HTML code using Ionic framework and Angular

I am currently working on developing a hybrid app using Ionic and Angular. I attempted to incorporate jQuery UI for drag-and-drop functionality, but unfortunately, it did not work as expected. Despite testing simple examples, the feature still did not func ...