Patch causing issues in AngularJS 1.6 due to modifications in Array.prototype.filter by monkeys

ngSwitchWhen Issue: Error Message 'Cannot read property 'NaN' of undefined'

After successfully implementing a filter method on the Array prototype with Angular 1.5.7, I faced an issue when upgrading to version 1.6.10. The same code that used to work is now throwing an error message

'Cannot read property 'NaN' of undefined'
in the browser console.

Snippet from HTML:

  <select ng-model="selection" ng-options="item for item in items">
  </select>
  <code>selection={{selection}}</code>
  <hr/>
  <div class="animate-switch-container"
    ng-switch on="selection">
      <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
      <div class="animate-switch" ng-switch-when="home">Home Span</div>
      <div class="animate-switch" ng-switch-default>default</div>
  </div>

Snippet from Controller:

 Array.prototype.filter = function (predicateFunction) {
   let results = [];
      this.forEach((item) => {
        if (predicateFunction(item)) {
          results.push(item);
        }
      });
    return results;
  };

  $scope.items = ['settings', 'home', 'options', 'other'];
  $scope.selection = $scope.items[0];

To reproduce this issue, you can view the example on Plunker.

Answer №1

There seems to be an issue with your custom implementation of Array.prototype.filter:

 Array.prototype.filter = function (predicateFunction) {
   let results = [];
      ̶t̶h̶i̶s̶.̶f̶o̶r̶E̶a̶c̶h̶(̶(̶i̶t̶e̶m̶)̶ ̶=̶>̶ ̶{̶
      this.forEach((item,index,array) => {
        ̶i̶f̶ ̶(̶p̶r̶e̶d̶i̶c̶a̶t̶e̶F̶u̶n̶c̶t̶i̶o̶n̶(̶i̶t̶e̶m̶)̶)̶ ̶{̶
        if (predicateFunction(item,index,array)) {
          results.push(item);
        }
      });
    return results;
  };

The correct way to handle the callback would be by passing three arguments:

  • the value of the element
  • the index of the element
  • the Array object being traversed

Update

According to the ES5 Standard, it is recommended to use this polyfill instead:

if (!Array.prototype.filter){
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
        throw new TypeError();
   
    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;
    if (thisArg === undefined){
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func(t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }
    else{
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func.call(thisArg, t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }
   
    res.length = c; // shrink down array to proper size
    return res;
  };
}

To learn more, visit MDN JavaScript Reference - Array.prototype.filter polyfill.

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

Modifying CSS property values by handling a returned validation error

Allow me to describe a scenario I've created. Please excuse any language errors in my explanation. I have designed a form for users to submit values. Within this form, users can choose an option - one of which is "Others specify...". When this option ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

Using AngularJS to bind radio buttons to ng-model

Here is a snippet of my HTML code where I attempted to bind the "formFriendsAll" scope to the ng-model. <form ng-submit="submitForm()" > <div class="col-sm-3"> <div class="form-group"> <label>Which Persons to show?< ...

Display the modal content while maintaining its current styling

When attempting to print a modal with specific data exactly as it appears, I encountered an issue where the Bootstrap classes were not being recognized during the printing process. This resulted in a change to the layout of the content printed. function p ...

Tips for incorporating a last or recently visited feature similar to Google Docs using MongoDB

Within my database, I have two collections: users and projects. These collections share a many-to-many relationship. One user can be associated with multiple projects and one project can be assigned to multiple users. In the user object, I store an array o ...

Leveraging JSON data in a client-side JavaScript script

Recently, I started exploring node.js and express. One issue that I am currently facing is how to correctly retrieve json data in a client-side javascript file. I keep receiving a 404 error indicating that the .json file cannot be found. In my project&apo ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

How can one display an integer value instead of a scientific value in an AngularJS view?

I came up with this handy function that handles the conversion from dp (density independent) to px (pixels): $rootScope.dp2px = function(dp) { if(!!dp) { var px = window.devicePixelRatio * dp / 160; return px.toPrecision(2); } else ...

Value entered is not being stored in the array

Currently, I am working on a program meant to help me get used to C style code compared to the C++ that I normally use. However, I have encountered an issue that is preventing progress. My problem lies in trying to populate an array with user input using ...

Tips on utilizing the event.preventDefault() method within AngularJS?

Recently, I stumbled upon a technique to prevent page refreshing after submitting a form by using event.preventDefault();. As someone who is still learning Angular, I am unsure of how to incorporate this syntax into my Angular controller. Is "event" some s ...

Video on Youtube keeps playing even after the overlay is closed

I successfully created an overlay with an embedded YouTube video that automatically opens when the page loads. Everything was going smoothly until I encountered a problem - when I close the overlay while the video is playing, the audio continues to play in ...

Combining and grouping objects by their IDs in a JavaScript array

Information: [ { "id": "ewq123", "name": "Joshua", "order": "Pizza" }, { "id": "ewq123", "name": "Joshua", "order": ...

AngularJS Element Connections

I have the following component: (function () { "use strict"; angular.module("application_module") .component('tab', { controller: 'TabCtrl', templateUrl: 'app/component/application/app-heade ...

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

Check if a value falls within the range of an array

Here is how my array is structured: [age-pref] => Array ( [0] => 31-35 ) To check if a student's age falls within this range, I use the following method: $search_age = $filters['age-pref']; list($age_fro ...

Interactive calendar using Php and Javascript/Ajax

Currently, I am working on a PHP calendar and have integrated Javascript/Ajax functionality to enable smooth scrolling between months without the need for page refresh. Interestingly, the calendar displayed as expected before implementing Javascript/Ajax, ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...

A dropdown menu generated from a Google Sheet script that allows for the input of custom text alongside predefined

Currently, I am working on creating a dropdown list that not only allows me to select items but also input free text. The code below enables me to choose an item from a selected range in Google Sheets. However, I am looking for a way to incorporate the f ...

Organize chat messages based on date using JavaScript

I came across a similar query, but it didn't resolve my issue. Check this out: How can I group items in an array based on date? My goal is to organize these chat messages by date after fetching them from the database using AJAX. The console displays ...

I could really use some guidance on how to begin with the Node.JS app file in BlueMix

After delving into JS tutorials, I feel comfortable with the syntax and approach. Now, my focus is on utilizing Node.JS to develop an app using BlueMix. While I consider myself proficient in Java, web programming is uncharted territory for me, leaving me s ...