There seems to be an issue with the functionality of array.filter() in JavaScript

When attempting to search on the md-contact-chips, I encountered an error stating that createFilterFor is not a function. However, I have already created it as a function as shown below. Is there any way to resolve this issue?

Essentially, I am trying to replicate this demo, but instead of manually entering the contact names, I am retrieving existing data from my database using an http call to replace the contacts' names. This is demonstrated in the code snippet: Account.getTastes(). However, after displaying the retrieved data in the md-contact-chip as shown in the images below, the querySearch function stops functioning.

HTML:

<md-contact-chips required ng-model="tags" md-require-match md-contacts="querySearch($query)" md-contact-name="name" md-contact-image="image" filter-selected="true" placeholder="Thai, Chinese, cheap, cafe and etc">
 </md-contact-chips> 

Controller.js:

$scope.querySearch = querySearch;
$scope.filterSelected = true;
$scope.allContacts = loadContacts();
 $scope.allContacts.then(function(contacts){
   $scope.tags = [contacts[0],contacts[1]]
 })

    /**
     * Search for contacts.
     */
     function querySearch (query) {
       var results = query ?
           $scope.allContacts.filter(createFilterFor(query)) : [];
       return results;
     }
    /**
     * Create filter function for a query string
     */
    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(contact) {
        return (contact._lowername.indexOf(lowercaseQuery) != -1);;
      };
    }

    function loadContacts() {
      var contacts;
      return Account.getTastes()
             .then(function(res) {
             contacts = res.data[0].tastes;
             return contacts.map(function (c, index) {
               var colors = ["1abc9c", "16a085", "f1c40f", "f39c12", "2ecc71", "27ae60", "e67e22","d35400","3498db","2980b9","e74c3c","c0392b","9b59b6","8e44ad","34495e","2c3e50"];
               var color = colors[Math.floor(Math.random() * colors.length)];
               var cParts = c.split(' ');
               var contact = {
                 name: c,
                 image: "http://dummyimage.com/50x50/"+color+"/f7f7f7.png&text="+c.charAt(0)
               };
               contact._lowername = contact.name.toLowerCase();
               return contact;
             });
             })
             .catch(function(error) {
               console.log("Error:"+error)
             });
    }

Answer №1

Successfully resolved the issue

The reason for the ongoing error is that my $scope.allContacts variable is a promise instead of an array, causing the .filter function to return an error stating that createFilterFor is not a function.

   $scope.allTastes.then(function(tastes){
   $scope.tags = [tastes[0],tastes[1]]
   $scope.allTags = tastes; // creating a new $scope to retrieve all tags from the promise
 })

    /**
     * Searching for contacts.
     */
     function querySearch (query) {
       console.log($scope.allTastes) // returns a promise 
       $scope.allTastes= $scope.allTags; // assigning it to $scope.allTastes, now containing the entire array 
       var results = query ?
          $scope.allTastes.filter(createFilterFor(query)) : [];
       return results;

     }

Grateful for all the assistance!

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 best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...

The IsArray() function in IE8 encounters an issue where it expects an error object

I am interested to know why IE8 is having trouble with this line of code: if (isArray(obj)) When I check in the IE8 javascript console, I see the following: >>obj {...} >>typeof(obj) "object" >>Object.prototype.toString.call(obj) "[obj ...

How can I keep the cursor in place while editing a phone number field on Sencha ExtJS?

After one backspace move, the cursor on the phone number field automatically moves to the end which can be inconvenient if the user only wants to edit the area code. Unfortunately, I am unable to post images at the moment due to insufficient reputation. B ...

Use JavaScript to change the text of a hyperlink to @sometext

<li class="some-class one-more"><label>twitter:</label> <a href="https://twitter.com/sometext?s=09" target="_blank" rel="noreferrer noopener">https://twitter.com/sometext?s=09</a> < ...

The issue persists with react-hook-form and Material UI RadioGroup as the selected value remains null

Having trouble with RadioGroup from Material UI when using react-hook-form Controller. I keep getting a null selected value, even though my code seems right. Can you help me figure out what's missing? import * as React from "react"; import { ...

Troubleshooting issues with the controller functionality in AngularJS

The following code is not producing the expected output of 'Hello, World' output: {{ greetings.text }}, world Could someone please assist me in determining why it is not displaying 'hello, world' as intended <!doctype html> ...

Is it possible to use NextJS to simultaneously build multiple projects and export them as static sites?

I'm currently working on a small Next.js project where I retrieve data from various API endpoints. These endpoints typically follow this format: https://enpoint.com/some-query/project1 The interesting thing about the API is that it can return differe ...

Encountering an issue where attempting to map through a property generated by the getStaticProps function results in a "cannot read properties

Greetings, I am fairly new to the world of Next.js and React, so kindly bear with me as I share my query. I have written some code within the getStaticProps function in Next.js to fetch data from an API and return it. The data seems to be processed correct ...

Getting Started with Angular 2 Installation

Looking for a straightforward way to incorporate Angular2 into a single HTML file without using Bower, NPM, NuGet, or other complex methods? EDIT: Thanks to Dieuhd's suggestion, I was able to make Angular 2.0 work using the following script referenc ...

Retrieve information from a pair of models

Hey there, I need some help. Can someone please guide me on how to obtain the 'topics' array and append it to res.view()? I've tried multiple approaches but keep getting 'undefined' in the 'topics' array. Subjects.qu ...

Steps for initializing textures in THREE.JS before use

Before beginning the rendering and animation of objects, I preload and create material textures. However, THREE JS only uploads textures to the GPU when the object is visible in the camera. This causes jerky animation when a new object appears on screen ...

Implementing two background images and dynamically adjusting their transparency

With the challenge of loading two fixed body background-images, both set to cover, I encountered a dilemma. The text on the page was extending below and scrolling, along with top and bottom navigation icons. As expected, the second background covered the f ...

Erase every picture contained within the element

<div id="uniqueidhere"> <span> <span><img src="image1link"></img></span> <span><img src="image2link"></img></span> <span><img src="image3link"></img></span> <span>&l ...

Tips for crafting a perpetually looping animated shape using canvas

Lately, I've been experimenting with canvas and have encountered a challenge that I can't seem to solve. I've mastered creating shapes, animating them, and looping them across the canvas. However, I'm struggling to figure out how to spa ...

Express fails to provide a correct response

I have been working on implementing MongoDB to gather data for our analytics page. However, despite seeing the data in the terminal through console log, when I make a request, Express returns an empty array as the response. Here is my endpoint: import Ana ...

Header on top of table that stays in place with scrolling

I'm facing an issue with a table that contains user-generated data. We are utilizing a plugin known as Clusterize, which allows us to smoothly scroll through large amounts of rows. However, the specific markup required for this plugin seems to be caus ...

Validate if the token has expired by utilizing this JWT library

My token configuration looks like this: jwt.sign( { user: pick(user, ['_id', 'username']) }, secret, { expiresIn: '2m' } ); However, when attempting to verify if the token has expired, the following code isn ...

What happens when AngularJS encounters real-time polymorphism during runtime?

An intriguing report by the Financial Times discusses how Shape Security, a Google-backed venture, is using shape-shifting code to outsmart hackers. Real-time polymorphism could revolutionize cyber security, attracting investors from major tech companies l ...

Doing server side function calls from the client in NodeJs

I recently embarked on a journey to learn web development and am eager to make server-side data changes when invoking client functions. Take a look at my sample server setup: const fs = require('fs'); const path = require('path'); con ...

Tips for retrieving the MenuItem name upon click event using Menu and MenuItem components in Material UI React

Utilizing MaterialUI's Menu and MenuItem components in a React project, I am looking to display the name of the menu item upon clicking on it. Upon inspecting event.currentTarget in console.log, it returns the entire list item: ListItem Image attache ...