Improved method for managing these arrays

I am working on a menu that contains three groups of checkboxes to filter items on a webpage. The groups are labeled as store, city, and level. When any checkbox is checked within these groups, the value gets added to the corresponding array in an object structured like this:

items = {
  store: [],
  city: [],
  level: []
}

By default, all items are visible and no checkboxes are checked. Upon checking or unchecking a box, the items get filtered first by store and city, followed by further filtering based on level. If no level boxes are checked, all levels are displayed; however, if any are checked, only the checked store/citys of the checked levels are shown.

For example, the object could be represented as:

itms = {
  store: [
    'north',
    'evans',
    'dodge'
  ],
  city: [
    'boston',
    'miami',
  ],
  level: [
    'gold',
    'silver'
  ]
}

The desired formatted string should look like this:

.north.gold,.north.silver,.evans.gold,.evans.silver,.dodge.gold,.dodge.silver,.boston.gold,.boston.silver,.miami.gold,.miami.silver,
- order doesn't matter

If the object were:

items = {
  store: [
    'north',
    'evans',
    'dodge'
  ],
  cite: [ 'miami' ],
  level: []
}

The resulting string would be:
.north,.evans,.dodge,.miami

To generate the correctly formatted string from the object, currently I am using inefficient iteration methods:

      for (let [key, value] of Object.entries(items)) {
        value.forEach(item => {
          if(key !== 'level') {
            finalSelectors.push(`.${item}`);
            if (key === 'city') {
              finalSelectors.push(`.${item}_child`);
            }
          }
        });
      }
      
      let selectorsArr = finalSelectors;
      const reFinalSelectors = [];
      const selectedLevels = items.level;
      if(selectedLevels.length) {
        if(items.city.length || items.location.length) {
          finalSelectors.forEach(selector => {
            selectedLevels.forEach(level => {
              reFinalSelectors.push(`.${level}${selector}`);
            });
          });
        } else {
          selectedLevels.forEach(level => {
            reFinalSelectors.push(`.${level}`);
          });
        }
        selectorsArr = reFinalSelectors; 
      }

I am new to array functions and unsure about more advanced ones like Array.reduce(). Any guidance or assistance on how to improve efficiency would be greatly appreciated.

Answer №1

It seems that the store and city arrays are handled in the same way by the algorithm, so they can be combined. Then, all you have to do is pair each of them with each level - a simple two-dimensional operation.

The only complexity arises when there are no elements in level; in that case, only the prefix (store/city) should be added instead of going through the level iteration.

const items = {
  store: [
    'north',
    'evans',
    'dodge'
  ],
  city: [
    'boston',
    'miami',
  ],
  level: [
    'gold',
    'silver'
  ]
};

const { level } = items;
const resultArr = [];
for (const prefix of items.store.concat(items.city)) {
  if (level.length) {
    for (const suffix of level) {
      resultArr.push(`.${prefix}.${suffix}`);
    }
  } else {
    resultArr.push(`.${prefix}`);
  }
}
console.log(resultArr.join(','));

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

Tips for identifying whether a form contains any empty fields and, if it does, directing focus to an anchor element

Is it possible to determine if a specific form contains any input fields? What about if it doesn't have any input fields? Additional Query: Also, how can I ensure that the focus is returned to a button when the page loads if the specified condition ...

Refresh the custom JavaScript dropdown list without having to reload the page

I implemented this code to customize a drop-down list Selector. Is there a way to reset this code without reloading the page, maybe by triggering a function with a button click? <button onclick="reset();">Reset</button> For example, if "Jagu ...

What about creating a PHP-MySQL voting platform?

I have implemented a PHP-MySQL voting system on my website, similar to YouTube's. I am using AJAX to execute the PHP in newtest.php. The PHP script works fine when tested individually, but when trying to implement the voting functionality through AJAX ...

Exploring the possibilities of wildcards in npm scripts on Windows

Currently, I am attempting to use jshint to lint all of my javascript files by utilizing an npm script command. Even though I am working on a Windows system, I am facing an issue where I cannot successfully lint more than one file regardless of the wildca ...

Using arrow functions in Vue Pinia getters to access other functions

sample shop getters: { setNewName: (state) => (string: string) => { state.user.username = string; }, updateUser: (state) => { setNewName('Tom'); // setNewName is not defined. } } Is there a way to access ...

Storing data using recursive methods in a controlled environment (Python)

My partner and I are currently tackling a challenge that involves reducing an array and performing operations on its segments in pairs using recursion. We have successfully achieved this, as demonstrated with the example array [2, 3, 4, 5, 6, 7, 8, 9] wher ...

Modify Bootstrap Card Styling Using JavaScript

When the clock strikes certain evening hours on my website, the Bootstrap card's default light style no longer fits the dark theme. I've attempted to switch the card to a dark style by tying in some JavaScript code, but it's not quite doing ...

JavaScript versus Non-JavaScript Links and Forms: A Comparison

The other day, I posted a query that got me thinking: Comparing AJAX link with normal link It revolved around the idea of creating links that function for JavaScript-enabled browsers using AJAX, while also providing a normal link for non-JavaScript brows ...

The issue with the Hidden Content feature in the Slick Carousel is that it does not function correctly on the

There are some related topics worth exploring, such as: Slick carousel center class not working when going from last item to first item Despite trying various solutions, the issue still persists in my code. My goal is to have each item displayed in the ce ...

Always ensure that only one div is visible at a time

I am currently working on a project where I cannot use ng-cloak due to the way the css files are loaded. I have been exploring alternative solutions and have tried a few different approaches. My main goal is to ensure that two icons are never shown at the ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

Is there a way I can create an object in JavaScript by using an array of values as parameters instead of having to manually list them out?

Can I achieve this? My goal is to develop a universal factory function that can generate different types of factories with some commonalities. I aim to pass arguments as an array to the base factory, which would then potentially create a new object instanc ...

What steps can be taken to prevent the "unable to convert undefined to an object" error from occurring?

There seems to be an issue with some of the documents not containing the planDetails and planId properties, resulting in the error "can't convert undefined to an object." However, I need to fetch that document whether these properties exist or not. Ho ...

Clicking on a link with an onclick method renders selenium ineffective in producing any action

The specified element is: <a href="#" onclick="submitViaAjax(null, url);return false;">Add</a> After using element.click() to try clicking the link, the onclick method fails to execute. Is there a way to ensure the method is executed success ...

How can I effectively exclude API keys from commits in Express by implementing a .gitignore file?

Currently, my API keys are stored in the routes/index.js file of my express app. I'm thinking that I should transfer these keys to an object in a new file located in the parent directory of the app (keys.js), and then include this file in my routes/in ...

Displaying 100,000 sprites with a faint 0.1 opacity, utilizing see-through backgrounds and crisp antialiasing

In my current setup, I have the following key pieces of code: Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, canvas: canvas }); Textures dot: THREE.ImageUtils.loadTexture('./assets/images/dot.png') Material ...

Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab. The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor fo ...

Timing of loading values into ng-if directive in AngularJS

While waiting for details to load, I have implemented a few ng-if directives on elements. This way, I can display a loading graphic to the user while the element value is undefined. Once the value is defined, the ng-if evaluates to false and hides itself. ...

The getUserMedia() function fails to work properly when being loaded through an Ajax request

When the script navigator.getUserMedia() is executed through regular browser loading (not ajax), it works perfectly: <script> if(navigator.getUserMedia) { navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __ ...