Using Typescript and Angular to efficiently filter an array of objects

I am dealing with an array of objects that contain a "category" attribute. My goal is to filter this array and retrieve only the objects with the "tech" category.

An error message is being displayed stating that "filter" does not exist on type {}

stocks-list.ts

import { Stock } from './Stock';

export const STOCKS: any[] = [
  { id: 11, symbol: 'AAPL', name: 'Apple', category: 'Tech' },
];

stock.service.ts

import { Injectable } from '@angular/core';
import { Stock } from './Stock';

import { STOCKS } from './stocks-list';

@Injectable({
  providedIn: 'root'
})


export class StockService {


  constructor() { }
  techStocks: Stock[];
  getTechStocks(): Stock[] {
    this.techStocks = STOCKS;


    return this.techStocks.filter(xx => xx.category = 'Tech');
  }
}

Answer №1

To make the correct comparison, you just have to replace xx.category = 'Tech' (which updates) with xx.category === 'Tech' (which tests equality)

Here is a simple example to demonstrate:

const stocks = [
  { id: 11, symbol: 'AAPL', name: 'Apple', category: 'Tech' },
  { id: 12, symbol: 'AAPL', name: 'Orange', category: 'Fruit' },
  { id: 13, symbol: 'AAPL', name: 'Not Apple', category: 'Fruit' },
];
console.log(stocks.filter(xx => xx.category = 'Tech'));

In this scenario, every element's category is being updated to 'Tech' (as seen in the output of the first snippet where all categories are now 'Tech'), and then you are returning 'Tech' to the filter function which always evaluates as 'true'

    console.log(foo = "bar"); // The assignment operation also returns the value
    console.log(!!foo); // A non-null value is evaluated as `true` (as boolean)

Therefore, your filter function will always check if (!!'Tech' === true) (always resulting in true), hence returning all elements that were updated.

The solution is simply to use === for the correct boolean evaluation

const stocks = [
  { id: 11, symbol: 'AAPL', name: 'Apple', category: 'Tech' },
  { id: 12, symbol: 'AAPL', name: 'Orange', category: 'Fruit' },
  { id: 13, symbol: 'AAPL', name: 'Not Apple', category: 'Fruit' },
];
console.log(stocks.filter(xx => xx.category === 'Tech'));

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

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

Creating secure routes with React Router

I am trying to restrict access to certain routes for administrators only. The goal is for admins to be able to access these private paths after successfully logging in. However, I am encountering an issue where upon login, the system redirects to an error ...

Caching HTML5 videos in Google Chrome

I am currently in the process of building a website and have successfully added an HTML5 video. However, I encountered an issue when attempting to change the video file in the background for users to upload a new one. Despite updating the video URL, Chro ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...

Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet: Index.php: <label>Select:</label> <sel ...

Using Javascript to organize information into a table with multiple columns

I'm looking to format a table using data retrieved from an ajax call, but I'd like the data to appear in columns instead of rows. Here is the code for the table body: <tbody id="tableData-marketMonth"> <tr> <th>Lead ...

Testing the creation of a new document ID using mocks in a cloud function unit

When it comes to Firestore cloud function TypeScript unit tests, my focus is on mocking doc().id, while leaving doc('path') untouched. Can anyone suggest how I can achieve this? admin.firestore().collection('posts').doc().id // Mocking ...

The React axios request triggers the UseEffect cleanup function to terminate all subscriptions and asynchronous tasks

I'm currently retrieving data from my API using axios, but the requests are not inside a useEffect function. In fact, I haven't used useEffect at all. Here's a snippet of my code: JSX: <form onSubmit={onSubmitLogin}> <div c ...

Discovering the value of a key within a JSON object by utilizing a String with JQuery

Given a JSON object, the challenge is to extract values based on user input. The input format will be similar to "data.location.type" or "data.location.items[1].address.street". Is it achievable using JQuery? { "data": { "location": { ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

The content could not be created due to an inability to lazily initialize a collection of roles. The proxy could not be initialized as there was no

Encountering an error with FetchType.LAZY: Error message: failed to lazily initialize a collection of role: com.websystique.springmvc.model.User.userProfiles, could not initialize proxy - no Session Here is the model class in question: @SuppressWa ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...

Handling typeError in Vue.js JavaScript filter for object manipulation

I need to sort an object based on state names (e.g. Berlin, Bayern ...). Below is the API response I received. "states":{ "Bayern":{ "total":13124737, "rs":"09", "va ...

How to declare multiple components in @ngModule using Angular 2

Currently, I'm working on a hefty project that combines Angular 2 with ASP.net MVC. I've got around 120 components declared within the @NgModule block like so: @NgModule({ imports: [CommonModule], declarations: [Component1, Component2, Comp ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Can you specify separate paths in your NPM package for use in the browser versus the server (NodeJS)?

Can you specify separate directories within your NPM package for the browser and NodeJS server? While my code is largely isomorphic, it’s minified and combined for browsers. ...

Is locking Node and npm versions necessary for frontend framework projects?

Currently working on frontend projects in React and Vue, I am using specific versions of node and npm. However, with other developers contributing to the repository, how can we ensure that they also use the same versions to create consistent js bundles? ...

What is the process for creating an Account SAS token for Azure Storage?

My goal is to have access to all containers and blobs in storage. The Account SAS token will be generated server-side within my Node.js code, and the client will obtain it by calling the API I created. While Azure Shell allows manual creation of a SAS toke ...

Babel exclusively processes JavaScript files in my Vue project, rather than the project as a whole

I need to make my Vue project compatible with an old iPad running iOS/safari version 5, which requires transpiling it to ES5 using Babel. Here is the content of my babel.config.js: presets: [ //'@vue/cli-plugin-babel/preset', ["@babel/ ...

"Struggling with a basic Javascript function to refresh parts of a web page by calling a .php

After spending several hours browsing the internet, I am still struggling to get this straightforward example to function properly. Could someone please lend me a hand? My goal is to use JavaScript to display the contents of a PHP file. The display should ...