Filter observable array through a promise

I have

  • An array of objects
  • A function
    permission(obj): Promise<boolean>

Is there a simpler way to filter this array based on the promise result?

I've experimented with different approaches, but the closest I got was

of(arr).pipe(
  switchMap(items =>
    from(items)
     .pipe(
       mergeMap(item =>
         fromPromise(permission(item)).pipe(
           map(show => ({show, item})),
           filter(data => data.show),
           map(data => data.item)
         )
       ))
     ));

However, this method seems overly complex.

I was hoping for a more concise solution like

of(arr).pipe(filterByPromise(permission))
, but I'm struggling to simplify it.

I have created a Stackblitz example here

StackBlitz code

import { of } from 'rxjs'; 
import { map, filter } from 'rxjs/operators';

// Mocked 3rd party function
function visible(obj): Promise<boolean> {
  return new Promise(resolve => {
    const shouldShow = obj.shouldShow < 30;
    resolve(shouldShow);
  });
}

const arr = [{
  shouldShow: 39,
  data1: 'abc',
  data2: 'bcd'
}, {
  shouldShow: 22,
  data1: 'cde',
  data2: 'def'
}];

of(arr).pipe(
  filter(obj => visible(obj))
).subscribe(result => console.log(result));

Answer №1

A useful suggestion was offered by JB Nizet, advocating the use of concatMap over mergeMap for maintaining item order. You can learn more about the difference between these operators here.

from(arr).pipe(
  concatMap(element => from(visible(element)).pipe(
    filter(show => show),
    map(() => element)
  ))
).subscribe(console.log);

Alternatively, you can utilize zip to transform the array, as demonstrated below. However, the former solution appears to be more elegant.

zip(...arr.map(obj => from(visible(obj)))).pipe(
  map(visible => arr.filter((item, i) => visible[i]))
).subscribe(console.log);

You can find a functioning example of both solutions here.

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

Is it possible to obtain a reference that can call an operator?

Is it possible to obtain a reference to an operator (like ===) in TypeScript? The reason behind this question is the following function: function dedup<T>(values: T[], equals: (a: T, b: T) => boolean): T[] { return values.reduce<T[]>((pre ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

This error message occurs when a Firestore Trigger in Firebase Cloud Functions encounters a Permissions issue: Error code 7 PERMISSION_DENIED due to

I've been working on integrating a Firebase Cloud Function to update a document in my Firestore database whenever another document is updated. The trigger is functioning correctly, but I'm encountering an error when trying to access the other doc ...

Struggling to retrieve the image URL from a TypeScript file

I'm currently developing a basic app in Ionic that will include a feature to display a list of registered users along with their profile pictures. These profile images are stored in Firebase storage. Although I have successfully retrieved the URLs fo ...

"Troubleshooting Console Errors in NextJS with TypeScript Integration and Fluent UI Components

I am currently working with NextJS, TypeScript, and Fluent UI. To set up the app, I used the command yarn create next-app --typescript. Afterwards, I incorporated Fluent UI into my project by running $ yarn add @fluentui/react. So far, I have not made an ...

Updating the state using setState is not succeeding as expected

I am facing an issue with the code below where I want to use a file selector input to manage the input file as a state, but the output is not as expected based on the comments. I need guidance on how to troubleshoot and correct this problem. const [file, ...

Having trouble with error popups in Typescript 3.7.2, React, and Material UI 4.5.1 Snackbars due to styling errors

Utilizing the material UI snackbar for displaying error pop-ups in my react application has been quite a challenge. Incorporating a container view where certain actions trigger errors, I aimed to implement my custom snackbar component when an error arises ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

How can I transfer data between methods within Angular?

Help Needed: I have a service file with two methods, each having its own API. I want to call the getData method within the deleteData method. Can anyone guide me on how to achieve this? .service.file getData(): Promise<PagedResult<Sites>> { ...

Clear all data from the app without needing to refresh the application

At this moment, our application utilizes location.reload as a method to effectively clear all observables of previous data. Are there any alternative solutions that are less cumbersome and do not require reloading the entire app? Is there a recommended a ...

A guide on updating the input value manually with Chakra UI's useNumberInput hook

I've implemented a customized number input component using Chakra UI's useNumberInput hook. However, I need the ability to manually update the input value provided by useNumberInput in case of a failed API call, reverting it to the last value sto ...

"Encountered a TypeError while attempting to send a server action to a custom

My custom form component, <ClientForm>, is built using Radix Primitives. "use client"; import { FC } from "react"; import * as Form from "@radix-ui/react-form"; const ClientForm: FC = (props) => ( <Form.Root {.. ...

ngTable select all data that has been filtered

I have encountered an issue with selecting only the rows from an ng-table that have been filtered. The current code filters the table rows successfully, but it also selects rows that are not displayed: Controller: let sampleData = [{id: 1, name: 'Jo ...

Classify Express v4 router as a class

Despite successful compilation and the server supposedly starting on the correct port, I encounter a "cannot access this route" error when attempting any of my registered routes. I've come up short in finding resources on using express with classes, ...

When using TypeScript, the ReactDOM.render function may not accept certain components

Summary In my TypeScript and React project, I have created the AppContainer.tsx component and exported it as default. In the file app.ts, where I am using ReactDOM to render it on the targeted dom element, I encounter some errors (refer to the image). For ...

Angular 2 Issue: @Input() Directive Not Recognized - Unresolved Reference Error

I am a beginner trying to grasp Angular2 concepts from ng-book 2(v49). Below is the code snippet from article.componenets.ts file: import { Component, OnInit } from '@angular/core'; import { Article } from './article.model'; @Componen ...

Creating a fresh dataset using a 2D array in node-gdal-async

I'm facing a challenge in JavaScript where I need to create a new dataset from a 2D array. Despite my efforts, I can't seem to figure out the necessary steps from the documentation. It seems that in order to create this new dataset, I must utili ...

An Unhandled Promise Error has occurred: TypeError - Unable to access the 'nativeElement' property as it is undefined

I encountered the following issue: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined. This problem arises when I attempt to include a div with an ngIf statement within a Google map: HTML: ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

Is it possible to retrieve cached data from React Query / Tan Stack Query outside of the React tree?

Currently, I am in the process of developing an error handler for our mobile app that will send user data to the server when unexpected errors occur. Previously, I was able to easily retrieve user information from a global state. However, after removing t ...