Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) {
    if (selectedTags[0]) {
        if (vm.tags[i].term_id === selectedTags[0].term_id) {
            vm.tags[i].border1 = true;
        }
    }

    if (selectedTags[1]) {
        if (vm.tags[i].term_id === selectedTags[1].term_id) {
            vm.tags[i].border2 = true;
        }
    }

    if (selectedTags[2]) {
        if (vm.tags[i].term_id === selectedTags[2].term_id) {
            vm.tags[i].border3 = true;
        }
    }
}

vm.tags contains a comprehensive list of tags, usually up to 20 or more. selectedTags, on the other hand, is an Array that can hold a maximum of 3 tags, which may have the same ids as some of the tags in vm.tags.

In cases where tags from selectedTag match with tags in vm.tags, I need to update the border value of those specific vm.tags.

Is there a more efficient approach to achieve this objective without repeating code like shown above?


Example of the selectedTags Array:

[object, object, object]

Individual Object structure within the Array:

{
    selected: true,
    term: "term_name",
    term_id: 2349506
}

Answer №1

Take a look at this code snippet below:

for (let i = 0; i < myList.length; i++) {
  for(let j = 0; j < selectedList.length; j++){
    if(selectedList[j].id === myList[i].id ){
      let variableName = 'style_'+ ( j + 1 );  
      myList[i][variableName] = true;
    }
  }
}

Answer №2

To enhance efficiency, you may consider transforming the usage of border1, border2, and border3 into an array format. This can be achieved by iterating over the vm.tags array and for each tag, iterate over the selectedTags array to compare their IDs. Upon finding a match, push the value of the iterator from selectedTags into a new borders array. A sample implementation is shown below:

for (var i=0; i<vm.tags.length; i++) {
    for(var j=0; j<selectedTags.length; j++) {
            if(selectedTags[j].term_id === vm.tags[i]) {
            // ensure the existence of the array before pushing values
            vm.tags[i].borders = vm.tags[i].borders || [];
            vm.tags[i].borders.push(j);
        }
    };
};

This solution hinges on your ability to restructure the usage of border1, border2, and border3 into a more adaptable array format with possible elements such as [0, 1, 2].

It is recommended to make this adjustment as managing numbered values within a data structure can become unwieldy in a short span of time.

Answer №3

Check out this code snippet showcasing the use of JavaScript's array map and filter functions to achieve a similar outcome, albeit with potentially less readability:

var addBorders = vm.tags.map(function(item, index) {
  if (selectedTags.filter(function(tag) { return tag.term_id === item.term_id; }).length)
    item['border' + (index + 1)] = true;

  return item;
});

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

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

1. Catalog of dual JSON inquiries2. Compilation of

I am struggling to understand the right way to proceed. When I run this query, I receive a JSON response containing file names: $.getJSON("http://api.server.com/my/?callback=?", function(data){ var results = []; $.each(data['resul ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

Step-by-step guide on loading an external javascript file once a webpage is fully loaded, and incorporating a function from it

After the initial page load, I have a need to incorporate an external JavaScript file into an HTML file. This is necessary because a variable in this external JS file only updates after the HTML file has fully loaded. Additionally, I want to utilize the fu ...

Validate the date selected in a dropdown menu using JavaScript

I'm still relatively new to Javascript, just working my way through some tutorials. I have three select boxes in my HTML form as shown below. HTML Form: <table> <form id="enrolment" name="enrolment" onsubmit="return datevalidate();" action ...

Exploring the functionality of custom hooks and context in asynchronous methods using React Testing Library

I'm currently testing a hook that utilizes a context underneath for functionality This is how the hook is structured: const useConfirmation = () => { const { openDialog } = useContext(ConfirmationContext); const getConfirmation = ({ ...option ...

Prevent scale animation for a specific section of the icon using CSS

I need help in preventing the scale animation of the :before part of the icon class from occurring when the button is hovered. The current behavior is causing the arrow to look distorted on hover... Link to the code on Codepen HTML <div class="se ...

"Step-by-step guide to building a webgrid or table to organize and display your

These are the HTML codes I have created: <table> <tr> <td><label style="text-align:left">Product Code:</label></td> <td><input type="text" id="productCode" value="" /> </td> </tr> & ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

Challenge with Angular date selection component

I am currently utilizing ngbdatepicker in my form. I want to save the date separately and retrieve it as shown below. <input class="form-control ngbfield custom-form-control" required [ngClass]="{'is-invalid':f.touched && birthDay.inv ...

When working with Firebase, I am required to extract data from two different tables simultaneously

When working with Firebase, I have the need to extract data from tables/nodes. Specifically, I am dealing with two tables - one called jobs and the other called organisations. The outcome I am looking for: I want to retrieve all companies that do not hav ...

Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order ...

The ref.on() method fails to trigger a response from a function, despite producing the intended outcome

I've been working on developing an app called workspace. I previously asked a question, but I've made more additions to the features now. One of the new features is a remarks system. After experimenting with different versions of my code, the ver ...

encountering a type mismatch error while trying to retrieve data from an array

While attempting to retrieve data from a nested array, I encountered the error "TypeError: Cannot read property 'value' of undefined". It seems like I might be calling back incorrectly as I am receiving both the output and the error message in th ...

Using jQuery to scroll within a table

I am currently working on a project that involves displaying specific data rows. To achieve this, I have decided to use a table. For a better understanding, you can check out a table demo here. The issue I am facing is that whenever I change the selected ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

Once the <a> element is clicked, ensure that the function finishes executing before attempting to click/process it again

Utilizing jQuery.get for AJAX requests, I trigger a server request when the user clicks on the <a> element. The response is then used to update the content within the <div id='aaa'>. However, if the user clicks on the <a> rapid ...

The position of a jQuery element gets reset when both the show and stop animations are used

When I use jQuery's .position() to place an element, everything works fine. But as soon as I display an animation and then cancel it with an ajax call, the position of the element resets. function displayMessage(msg) { var $messageEl = $('#u ...

Opacity error with jQuery slider specifically affecting Google Chrome browser

My Magento site features a custom-built slider that is both responsive and has unique touch behavior. The desired behavior for the slider is as follows: A three-image slider where the middle image has an opacity of 1.0, while the other two images have an ...