Exploring Filtering, Slicing, and Sorting Techniques with Angular Factory in JavaScript

I am currently working on generating a filtered, sorted, and sliced list of data items in my Angular application. After successfully sorting and slicing the data, I encountered an issue when using dataHandler.filter. The error message

'Cannot read property 'slice' of undefined'
is being displayed.

Within my controller, I am attempting to create a new list by executing these functions:

Controller

getData().then(function(data) {

    function updateChart() {
        // obtain filter value
        var filterValue = inputService.primaryInputs[0]["value"];

        // apply filtering based on description match
        var filtered = dataHandler.filter(data, "Description", filterValue);

        // sort by descending percent value
        var sorted = dataHandler.sort.descending(filtered, "Percent");

        // display only top 5 results
        var sliced = dataHandler.slice(sorted, 5);
        $scope.barData = sliced;
    }
    updateChart();

});

I have verified that dataHandler.sort.descending and dataHandler.slice are functioning correctly as intended. However, encountering issues specifically with filtered when used as an argument in dataHandler.sort.descending, resulting in the aforementioned error.

Factory

app.factory('dataHandler', function ($rootScope) {
    return {
        filter: function(data, dataProp, input) {
            data.filter(function(value, index, array) {
                console.log(value[dataProp] == input);
                return value[dataProp] == input;
            });
        },
        sort: {
            ascending: function (data, sortCriteria) {
                if (data) {
                    data.sort(function (a, b) {
                        return a[sortCriteria] - b[sortCriteria];
                    });
                };
                return data;
            },
            descending: function (data, sortCriteria) {
                if (data) {
                    data.sort(function (a, b) {
                        return b[sortCriteria] - a[sortCriteria];
                    });
                };
                return data;
            }
        },
        slice: function (data, howMany) {
            if (howMany) {
                return data.slice(0, howMany);
            } else {
                return data;
            }
        }
    };

In essence, I am looking to utilize dataHandler.filter to refine the list based on matching criteria from the Description values to the filterValue.

Answer №1

The issue lies in the fact that your dataHandler.filter function is not returning anything.

It should be:

filter: function(data, dataProp, input) {
  return data.filter(function(value, index, array) {
    console.log(value[dataProp] == input);
    return value[dataProp] == input;
  });
}

Keep in mind that Array.prototype.filter does not modify the original array.


While this solution will work, I recommend avoiding a factory for these tasks. Filtering, slicing, and sorting are general-purpose tasks and don't require wrapping around native implementations unless you are polyfilling.

Instead of a factory, consider creating a service with reusable transformation functions that can be chained together for operations.

.service('Transform', function() {
  // Function passed to filter
  this.propEquals = function(property, value) {
    return function(data) {
      return data[property] === value;
    };
  };

  // Function passed to sort
  this.sort = function(criteria, ascending) {
    return function(a, b) {
      return ascending?
        a[criteria] - b[criteria] : b[criteria] - a[criteria];
    };
  };
})

Then, update your updateChart method as follows:

function updateChart() {
  var filterValue = inputService.primaryInputs[0]["value"];

  $scope.barData = data
    .filter(Transform.propEquals("description", filterValue))
    .sort(Transform.sort("Percent", false))
    .slice(0, 5);
}

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 integrating Google Analytics with React

In my react application, I have various pages: Main Service Contact Profile (private) etc.. To monitor user activity using Google Analytics, I came across the react-ga library which serves the purpose well. However, I find myself having to initialize G ...

Fade in text and then vanish after a few moments

I am looking to implement a fading in and out effect for text that stops after a certain period of time. The goal is for the text to indicate that a user is online when they join, and then disappear after some time. Currently, the function does not have a ...

Developing a Fresh Settings Tab and Vue Module in Laravel Spark

When working with Laravel Spark, you'll find that most settings panels come with a corresponding Vue JS component that is called upon using a custom tab. <spark-create-tests :user="user" inline-template> <div> </div> </sp ...

Display a DIV element when a specific date is chosen using bootstrap-datepicker

Looking to incorporate the bootstrap-datepicker plugin using the provided markup... Is there a way to display a DIV element when selecting a specific date and then hide it again when another date is chosen? <head> <script src="https://cdnjs.cl ...

What is the process for swapping out a file input tag with a specific file already chosen?

As I attempt to process a file one line at a time, I came across this helpful solution. Unfortunately, the method involves using a file input tag to choose a file for reading. I am in search of a way to bypass the file input tag and specify a file in advan ...

When performing web scraping with Puppeteer, employing a single selector to target various types of data

As a budding web developer, I have recently delved into coding. My current knowledge is limited to HTML, CSS, JS, and NODE. Currently, I am working on a project involving page scraping and utilizing puppeteer. CHALLENGE - In scenarios like the o ...

Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Displaying dates on the Amcharts category axis for instances with empty data

I am currently creating a fruit consumption chart for each day, and so far everything is working correctly in the provided example. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "hideCredits": true, "fixedColumnWidth": '10px& ...

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

The D3 data format allows for creating interactive sunburst charts that can be easily zoom

My data is structured similarly to flare.json as shown in this example: I'm curious about the function used by the d3 zoomable chart to format the data in this way. The original structure in flare.json looks like this: { name: "stuff", childr ...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

Having trouble with the ajax cache not working properly when trying to load an image

I am attempting to dynamically load an image from the server every time a button is clicked using a GET request. However, I am facing an issue where the cached image is being loaded instead of the latest version. Below is the code I am currently using: & ...

Iterate over a series of spreadsheets

I am encountering an issue while attempting to iterate through a series of sheets. Specifically, I am facing an error when trying to select sheets within a range on a certain sheet. Sub LoopThroughSheets() Dim sheetnames As Variant sheets("LoopThroughShe ...

JavaScript can be used to select and click on a specific li element using the :

I'm attempting to click on a specific link using a submit button. Essentially, I have a ul containing a large number of li elements, each with a link of class "episodeLink" inside, as shown on . I've added an input box where you can enter a num ...

The response from the Ajax request showed that the data was not

I am working on a page where I need to refresh a specific div every minute without refreshing the whole page. The div retrieves data from a PHP file that calculates the highest price in another XML file. I have learned that the most effective way to achiev ...

Hiding the icon if there are no child elements present

Currently, I am in the process of constructing a TreeView using the Treeview component from Material UI, which can be found at this link. The component I have designed below is responsible for fetching data when a node is expanded. The tree structure is s ...

The $.get jQuery function is unexpectedly retrieving an entire HTML page instead of the expected JSON data

Currently, I am in the process of developing a web application and have opted to use PHP as the server-side language. Below is the PHP script responsible for returning JSON data: <?php require_once "connection.php"; if (isset($_GET['take'])) ...

Saving the id in a variable after triggering an AJAX request by clicking

I attempted to utilize an onClick event within the <a> element but it is not functioning as expected. I am aiming to capture the value 777 into a variable so that I can access it later in the code. My intention was to click on the image and have an ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...