Locate and Remove item from an array based on initial characters

How can I remove an element from a dynamic array if it already contains an element with the same letters, and then push a new element? Here is my code:

    $scope.selectedCat = [];
        $scope.selectedCl = [];

        $scope.updateCategory = function (categoryId) {

            if ($scope.selectedCat.indexOf(categoryId) > -1) {
                $scope.selectedCat.splice($scope.selectedCat.indexOf(categoryId), 1);
            } else {
                $scope.selectedCat.push(categoryId);
            }

           $scope.queryCategory = 'categoryId=in=(' + $scope.selectedCat + ")"
          // console.log($scope.queryCategory)
            //Optional, to reload on change.
          $scope.requestSelected ($scope.queryCategory)

        };

        $scope.updateClass = function (classId) {

            if ($scope.selectedCl.indexOf(classId) > -1) {
                $scope.selectedCl.splice($scope.selectedCl.indexOf(classId), 1);
            } else {
                $scope.selectedCl.push(classId);
            }

             $scope.queryClass = 'eventClassId=in=(' + $scope.selectedCl + ")"
            // console.log($scope.queryClass)
            //Optional, to reload on change.
            $scope.requestSelected ($scope.queryClass)

        };


        $scope.filter = []
        var string;
        $scope.requestSelected = function (param){

       if($scope.filter already has an elem with the same letters as param){

         // delete this elem then 

         $scope.filter.push(param)
      } else {

         $scope.filter.push(param)

    }

          // final result 
          string = $scope.filter.join(";")

          console.log(string)

        }

UPDATED With help from @Anton, I have completed the logic for creating a correct request. This code is now working in the updated plunker. Hopefully, this will be useful for someone.

Answer №1

It is important to structure your search fields properly by separating the conditions for each field. Avoid adding conditions directly in the code like $scope.filter.push(param). Instead, create separate fields for different search criteria as shown below:


var filterOptions = {
    filterBy: '&$filter=',
    filterParam: "",
    classId: '',
    categoryId: ''
};

$scope.selectedCat = [];
$scope.selectedCl = [];

$scope.updateCategory = function (categoryId) {

    if ($scope.selectedCat.indexOf(categoryId) > -1) {
        $scope.selectedCat.splice($scope.selectedCat.indexOf(categoryId), 1);
    } else {
        $scope.selectedCat.push(categoryId);
    }

    filterOptions.categoryId = 'categoryId=in=(' + $scope.selectedCat + ")"

    filterOptions.filterParam = filterOptions.classId + ";" + filterOptions.categoryId
    console.log(filterOptions.filterParam)
};

$scope.updateClass = function (classId) {

    if ($scope.selectedCl.indexOf(classId) > -1) {
        $scope.selectedCl.splice($scope.selectedCl.indexOf(classId), 1);
    } else {
        $scope.selectedCl.push(classId);
    }

    filterOptions.classId = 'eventClassId=in=(' + $scope.selectedCl + ")"

    filterOptions.filterParam = filterOptions.classId + ";" + filterOptions.categoryId
    console.log(filterOptions.filterParam)

};

Answer №2

Give this a shot

//Let's create a new array and add elements to it
$scope.filter = []
$scope.TempArr = [];
var string;
$scope.requestSelected = function(param) {
for (var i = 0; i < $scope.filter.length; i++) {
  if ($scope.filter[i] == param) {
    $scope.TempArr.push(param);
  } else {
    $scope.TempArr.push(param);
  }
  if (i == $scope.filter.length - 1) {
    //$scope.filter=[]; if you want then you can update new element only
    $scope.filter = $scope.TempArr;
    string = $scope.filter.join(";")

    console.log(string)
   }
  }
}

Answer №3

To the best of my knowledge, one way to achieve this (simplified names and function calls) is:

var filter = ["abc", "123"], param = "_?!"

var found = filter.indexOf(param);
if (found !== -1) {
  // There is already an element in the filter array with the same letters as the param
  filter.splice(found, 1);
}

filter.push(param);

Have I overlooked any subtleties in this approach?

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

Incorporating PruneCluster into an AngularJS Leaflet Directive for Enhanced Mapping

I am currently facing an issue with loading clustered markers for geojson data using PruneCluster. The clusters are not appearing on the map and there are no errors showing up in the console to assist with troubleshooting. Below is the snippet of my curr ...

Unable to retrieve the updated array value in NodeJs when accessed outside the function scope

I recently started working with node and I'm attempting to retrieve the Twitter id of a group of users. The module takes an array of screen names, iterates over them to obtain the userId, and then adds them to an array. However, I'm facing an iss ...

Issues arise when building with Angular using `ng build`, but everything runs smoothly when using `

My Angular 5 application uses angular-cli 1.6.8 { "name": "test", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "karma": "ng test", "test": "jest", "test:watch": "j ...

The KoGrid filter is malfunctioning when used in conjunction with Plunker

I'm currently facing an issue with the filter functionality on the knockoutjs ko grid. There are a couple of issues that I've encountered: Firstly, the drop-down menu for the filters displays "Choose columns" but the column names get cut off at ...

The JSON object contains arrays that I send to the server side using an AJAX call. I am wondering how I can access this data once it has been sent

$scope.addQunatity = function(){ var url="../php/mainPageFacture.php"; // store data from user in the js arrays var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()]; var quan_piece=[$("#quan_piece").val(),$("#quan_piece2" ...

Iterate through the array and append information

My challenge involves working with an array named "content". Within this array, there is the "asin-id," which serves as a product ID. My goal is to iterate through the content array, retrieve the specific product associated with the asin-id, add the produc ...

Guide on efficiently mapping an array containing arrays and simply retrieving the result

I am working with an array of arrays and I need to extract the values from each array. However, when I try to map over the arrays, I end up with just a single array and I'm not sure how to access the individual values. const arr = [ [1, 2, 3], ...

Express.js - display the complete information

Trying to display an array of objects (highcharts points) is giving me some trouble. Instead of the actual data, I'm seeing [object Object]. It seems that JSON.stringify() doesn't play well with HTML. util.inspect also doesn't work as expe ...

The efficiency of the react native Animated.spring function leaves much to be desired, as it

I am currently using the React Native animated API to create a seamless transition from left to right positions. This is how I set up my initial state: constructor(props) { super(props); this.state = { isDrawerOpened: false, ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

Interactive Icon Feature Instead of Annoying Pop-Ups in JavaScript

Hello there! I need assistance fixing a code issue. Currently, the code automatically pops up when the page is opened. Is there a way to make it clickable instead of popping up automatically? <script type="text/javascript" src="//www.klaviyo.com/media/ ...

Tips for converting a "callback pyramid" into a promise-based structure

I'm currently struggling with understanding how to refactor my code to use promises or the Q library effectively. Let's consider a common basic example: I have a test case that imports the same file twice into a MongoDB database and then checks ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

Fluctuating between different currencies

I have been trying to tackle this issue for some time now - how can I set up the functionality to switch between currencies seamlessly? The first select dropdown should include options for EUR, USD, and GBP, while the second should offer UAH, GBP, and EUR. ...

What is the recommended placement for the implicitlyWait method in Protractor?

When implementing implicitlyWait, what is the appropriate location to include browser.manage().timeouts().implicitlyWait(5000); within the test script? ...

The function is not specified

Currently, I am in the process of implementing a login system using nodejs. My goal is to define a global function outside of a module and then call it multiple times within the module. However, I am encountering an issue where it always returns undefined, ...

Is there a way to efficiently line up and run several promises simultaneously while using just one callback function?

I am currently utilizing the http request library called got. This package makes handling asynchronous http connections fast and easy. However, I have encountered a challenge with got being a promisified package, which presents certain difficulties for me ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...

Ways to set up Vue data() by leveraging the value of an HTML input element

I'm looking for a way to set the initial value of Vue data() using the value from a rendered input tag. While I know that I can sync the value of the input tag with the data using v-model="[data-key-here]" in Vue, is there a method to initia ...