Tips for ensuring that .scan() aggregates only the most recent emitted array in a sequence that has not yet completed

I am faced with the challenge of transforming and aggregating elements in an observable array that is continuously open (network-based) and may never complete.

Currently, my code involves the following:

const numbers = [1,2,3];
const numbers$ = new Rx.Subject();

const output = numbers$
  .flatMap(n => n)
  .map(n => n*n)
  .scan((acc, x) => acc.concat([x]), [])
  .subscribe(n => { console.log(n); });

numbers$.next(numbers);

setTimeout(() => {
  numbers$.next([5,6,7])
}, 1000);

At present, multiple arrays are being emitted and the final emitted value is currently [1, 4, 9, 25, 36, 49]. However, my goal is to only square values that are part of the same input array.

In other words, I am looking for the output observable to emit two arrays: [1,4,9] and [25, 36, 49].

Does anyone have a solution to achieve this?

Answer №1

If you're searching for the solution, this could be what meets your requirements:

const result = numbers$
    .map((a) => a.map(n => n * n))
    .subscribe(n => { console.log(n); });

Note: In case you prefer not to utilize Array.map, an alternative approach using RxJS is available.

You have the option to swap out Array.map with an observable that squares the values and then compiles them into an array again. Moreover, further enhancements can be made by integrating distinct or other RxJS operators (as noted in your comment):

const result = numbers$
    .mergeMap(
        (a) => Rx.Observable.from(a)
            .map((n) => n * n)
            .reduce((acc, n) => { acc.push(n); return acc; }, [])
    )
    .subscribe(n => { console.log(n); });

Regarding the solution you provided:

const result = numbers$
    .flatMap(n => n)
    .map(n => n*n)
    .buffer(numbers$.delay(1))
    .subscribe(n => { console.log(n); });

This solution relies on timing and the reason why arrays are not merged together is due to the interval between the first next call and the second one exceeding one millisecond.

Answer №2

Here is a great resource for you: jsfiddle

const fruits = ['apple', 'banana', 'orange'];
const fruits$ = new Rx.Subject();

const result = fruits$
  .map(fruits => fruits.map(fruit => fruit.toUpperCase()))
  .scan((acc, x) => acc.concat([x]), [])
  .subscribe(fruit => { console.log(fruit); });

fruits$.next(fruits);

setTimeout(() => {
  fruits$.next(['grape', 'melon', 'kiwi'])
}, 1500);

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

Every time I attempt to reference the camera position in three.js, I am only able to access the initial position and not the present location

I am currently modifying a path file in THREEJS for a 3D art gallery project. My goal is to ensure that the camera always faces perpendicular to the path it follows, rather than allowing users to adjust the camera target with the mouse as in the original f ...

Storing a nested array in a database using PHP and Laravel

In my extensive form, I am sending 3 arrays to the controller: product_code | quantity | cost. $id = $request->get('product_code'); // RETRIEVE PRODUCT DATA FROM POST ARRAY $qty = $request->get('quantity'); // GET QUANTITY D ...

How can I trigger an Onclick event from an <a tag without text in a Javascript form using Selenium?

Here is my original source code: <a onclick="pd(event);" tabindex="0" issprite="true" data-ctl="Icon" style="overflow: hidden; background: transparent url("webwb/pygridicons_12892877635.png!!.png") no-repeat scroll 0px top; width: 16px; height: 16px ...

Having trouble accessing the menu in the dropdown div when clicking back?

I am working on creating a menu that drops down from the top of the page using JQuery. I have everything set up with the code below: <div id="menu"> <div id="menucontentwrapper"> <div id="menucontent"></div> </di ...

Issues with webkit css transitions not functioning as expected

Having a bit of trouble with my css transition animation. Attempting to animate the transform through jquery, and it's working well except for the webkit-browsers. I prefer not to use a class for the animation, but rather need to accomplish it using j ...

What is the best way to read a file, divide it based on specific criteria, and then save it into a list in Scala?

As a beginner in Scala, my current task involves parsing a file with the following content: You can't legislate morality... but it seems that morons can be legislators. Lottery: A tax on people who are bad at math. These are questions for action, no ...

Ways to change user input into a string and locate the position of the first two characters

I'm new here and haven't found a specific answer to my question, so I apologize if I'm not following protocol. My question is about converting text from a form input into a string and extracting a substring from that text. For example, if ...

What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...

How can we modify a string that is located outside of a loop?

While working on a C program that takes input of a string ogplaintext and a key, then produces a ciphertext as output, I encountered an issue. The loop in the code snippet is not only impacting the ciphertext variable but also changing the ogplaintext. Thi ...

Is it possible to have multiple React apps (components) displayed together on a single page?

I am looking to create some basic components for integration into an existing webpage. My plan is to begin with the default create-react-app setup. Ultimately, I aim to have src/FirstComponent.js and src/SecondComponent.js as products of this development p ...

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...

Building a sub route in React Router v4 allows developers to efficiently organize and manage

Before starting, I familiarized myself with the concept of react router by visiting https://reacttraining.com/react-router/web/guides/quick-start. I have developed a simple 3-page site in react and now want to create a list that will allow me to display so ...

Aggregating JSON data by comparing and combining corresponding keys

Before appending to a JSON object, I want to compare the values of keys and if they are the same, add the values together instead of simply appending. Here is the current structure: {"carset": { "location1": [ {"car": "vol ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

The tablesort feature is experiencing difficulty sorting tables with dynamically changing content

I have a question about sorting columns in a PHP file that calls a JS file. The PHP file contains two tables with the table sorter plugin implemented, but one of them works and the other doesn't. The working table is populated through an Ajax call, wh ...

When using an HTML dropdown select to display a list of generated users, only the value of the first user

I have a template that fetches a list of users from the database, and each user row contains a dropdown select option to change their user type (this is an admin page). My goal is to make the dropdowns submit the changes asynchronously. Currently, I can on ...

What is the best way to implement an onclick method on a div in order to toggle the display of information

I have come across similar questions, but in my case, I am working with dynamic data from an API. I want the message body to show when a user clicks on a message with only the subject, and then be able to click again to hide the body. The current functio ...

Populate the second dropdown menu with options determined by the selection in the first dropdown

I previously raised a similar question, but I am facing an issue with populating a dropdown list using PHP/MYSQL. Now, I aim to update the dynamic values in another dropdown based on the selection made here. My assumption is that I will need to utilize AJA ...

Can someone explain what logForm.$invalid.$setValidity is all about?

The code snippet can be found here I am a beginner in this field and currently studying a piece of code. I am having trouble understanding the logForm.$invalid.$setValidity line. I have searched online but couldn't find any information about it. The ...

Retrieving information from a URL stored in a JSON document

Trying to access data from a JSON file whose URL is nested in another JSON file can be quite complex. Let me simplify what I'm looking for: I want to retrieve all the contributors and the last hundred commits of a specific repository on GitHub. To a ...