Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids.

I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based on the id being more than 4 digits. In such cases, the full name, name, short name, and id should be removed. For example, if the id is 123456, it along with the name and short name should be filtered out.

app.js

  abc: {
      name: "Momo",
      value: "kls",
      long: "KLSE",
      searchRef: KLSE_SEARCH_REF,
      searchRefURL: "http://www.bursamalaysia.com/searchbox_data.json",

    },

details.js

$ionicLoading.show();

if ($scope.currentMarket == "abc"){

    $webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(function success(response){
        response = JSON.parse(response);
        for (var i = 0; i < response[0].length; i++){
            $scope.searchRef.push({
              name: response[0][i].name || response[0][i].full_name,
              symbol: response[0][i].short_name,
              code: response[0][i].id,
              market: $marketProvider[$scope.currentMarket].long
            });
        }
        console.info($scope.searchRef);
        $ionicLoading.hide();
    });
}

html

<div class="list">
    <div class="item" ng-repeat="item in searchItems" ng-click="openDetail(item)">
        <p>{{item.symbol}} - {{item.name}}</p>
        <p>{{currentMarket | uppercase}}</p>
    </div>
</div>

Answer №1

An elegant solution is to utilize Array.prototype.filter and Array.prototype.map.

$ionicLoading.show();
  if($scope.currentMarket == "abc") {
    $webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(
      function success(response) {
        $scope.searchRef = JSON.parse(response)[0].filter(function(itm) {
            // Add condition for filtering
            return itm.id.toString().length <= 3; 
        }).map(function(itm) {
            // Transform each item
            return {
              name: itm.name || itm.full_name,
              symbol: itm.short_name,
              code: itm.id,
              market: $marketProvider[$scope.currentMarket].long
            };
        });

        $ionicLoading.hide();
      }
    );
  }

Remember to handle errors and ensure your code is defensive.

Answer №2

If your requirement is to filter out ID values with more than 4 digits, you can easily achieve this by implementing a simple condition if(response[0][i].id <= 999). See the example below for reference:

for(var i=0; i<response[0].length; i+=1){
   if(response[0][i].id.toString().length <= 3 ) {
      $scope.searchRef.push(
        {
          name: response[0][i].name || response[0][i].full_name,
          symbol: response[0][i].short_name,
          code: response[0][i].id,
          market: $marketProvider[$scope.currentMarket].long
        }
      );
    }
    }

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

What is the proper way to connect with the latest Set and Map objects?

Can Angular 1.* ng-repeat function with Set and Map new objects? Is there a roadmap to implement this integration? ...

Leveraging an AngularJS variable within an iframe

Is it possible to use a variable inside an iframe src or ng-src attribute? I've tried different variables but none seem to be recognized. For example: <iframe ng-src="http://www.example.com/?name={{test}}"> </iframe> The variable test ju ...

`Troubleshooting a rotation problem with PhysiJS`

I've recently started working with this library and I've run into a persistent issue that has been quite challenging for me. My current setup involves two cubes, one utilizing physi.js and the other using three.js. I have a function in place to ...

Using AJAX to dynamically load Javascript

I came across this interesting code snippet: <script type="text/javascript" language="javascript"> $(function(){ $(window).hashchange( function(){ window.scrollTo(0,0); var hash = location.hash; if (hash == "") { hash="#main"; } ...

The React Native Android app encountered an error loading the JS bundle: updates made to index.android.js are not reflecting in the generated APK file

Setting up a react-native android project on my Windows machine has been successful so far. To run the project, I use the command react-native run-android and then the installed apk is generated on my phone. After making some changes in the index.android. ...

ReactJS is in need of extracting certain values from a promise

Within my Firebase database, I have organized data into two Documents: "users" and "posts". Each post in the "posts" collection is linked to a specific user using their unique id from the "users" collection. My goal is to retrieve user data associated wi ...

How can I resolve the issue of a lengthy link spanning two lines in Internet Explorer, while displaying correctly in other browsers on a Bootstrap navigation

Currently in the process of developing a responsive website with Bootstrap. The navigation buttons at the top are displaying correctly in Chrome, Safari, and Firefox, but in IE, the button labeled "Public Consultation" is wrapping onto two lines. I suspec ...

Accessing the element within an ion-tab using document.getElementById

Within my ion-view, I have ion-tabs containing a canvas element. However, when attempting to retrieve the canvas using document.getElementById('photoCanvas'); I receive 'undefined'. Here is the code snippet: HTML: <ion-view ...

Eliminate incorrect or invalid state when resetting a dropdown in an Angular ng-select component

I have integrated the ng-select plugin into my Angular project for handling dropdowns. One specific requirement I have is to reset the second dropdown when the first dropdown is changed. Below is a snippet of the code: <ng-select [items]="branchMo ...

What is the best way to create a line break within a loop in React?

I have a react component that I need to format into multiple lines, specifically having 2 boxes on top and 3 below in a looped return. The desired layout is to stack the boxes in 2x2 or 2x3 depending on the total number of boxes generated by the loop. So, ...

retrieve: add elements to an array

I'm having trouble identifying the issue here. I am fetching some json data (using a text file) and trying to push it into an array in the global scope. Even though I iterate over the json and push entries to the array, when I log it out, it appears e ...

Refresh the page once the function has been executed

Recently, I came across a basic javascript code that I need some help with. I want to reload the page after certain elements have faded out and back in. The problem is, I'm not sure where exactly I should include the window.location.reload(); function ...

Dealing with interstitial advertisements on mobile devices: What is the best approach for handling zoom?

I am facing a challenge with displaying interstitial ads on mobile sites. Different publishers may have varying viewport settings and initial scales on their mobile sites, making it difficult to ensure that the ad appears correctly on all devices with the ...

Effortless script to make a URL request and display the response status | using JavaScript with jQuery

Is there a way to use JavaScript or jQuery to request a URL or website address and display the response code? For example: request www.google.com if (response_code = 200) { print "website alive" } else if (response_code = 204) { print "not found"; } ...

Converting PlayFramework objects to JSON representations

Referenced Link: Utilizing Playframework in Scala: case class Location(lat: Double, long: Double) case class Place(name: String, location: Location) object Place { var list: List[Place] = { List( Place( ...

It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :) Below is the html and js code: $(do ...

Ensuring Smooth Transfer: Sending Local Storage Data to MVC Controller

I'm attempting to send an array of strings from my local storage (key value) to an MVC controller. Here's the code I have so far: Inside the cshtml View file: <script> function getFavouriteBooks() { var ids = JSON.par ...

Word.js alternative for document files

I'm on the lookout for a JavaScript library that can handle Word Documents (.doc and .docx) like pdf.js. Any recommendations? UPDATE: Just discovered an intriguing library called DOCX.js, but I'm in search of something with a bit more sophistic ...

What is the best way to resize an element such as an image?

When an image is resized using a percentage, it preserves its aspect ratio properly. I am looking for a way to replicate this behavior with a div. My current challenge involves precisely positioning an element relative to an image. The image fills 100% of ...

Acquire the worth of the <MenuItem> element from React's mui/material library

I am attempting to retrieve the value of the selected item listed below: Here is my attempt at logging this information: console.log("Event: ", event.currentTarget); Output: <li class="MuiButtonBase-root MuiMenuItem-root MuiMenuItem-gut ...