Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array in RxJS

RxJava has a method toSortedList(Comparator comparator) that converts a flow of objects into a list of objects sorted by a Comparator.

How can I achieve the same in JavaScript with RxJS and get an Observable with a flow of objects to emit a sorted array/list?

like image 540
Giorgio Avatar asked Oct 22 '15 09:10

Giorgio


People also ask

What is pipe() in rxjs?

log(x)); // Logs // 1 // 4 // 9. You can use pipes to link operators together. Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

How do you sort an array of objects in Javascript?

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

What is of Operator in rxjs?

The of Operator is a creation Operator. Creation Operators are functions that create an Observable stream from a source. The of Operator will create an Observable that emits a variable amount of values in sequence, followed by a Completion notification.

What is Observable pipe?

The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method. In this tutorial, we will take a look at the pipe and learn how to use it in an Angular Application.


2 Answers

With [email protected]

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

const obs = of(5,8,7,9,1,0,6,6,5).pipe(
  toArray(),
  map(arr=> arr.sort((a,b) => a - b)
);


obs.subscribe(x => {
  console.log(x);
});

outputs [0, 1, 5, 5, 6, 6, 7, 8, 9]

like image 199
Dan Beaulieu Avatar answered Oct 04 '22 22:10

Dan Beaulieu


you can use the code following:

Rx.Observable.of(5,8,7,9,1,0,6,6,5).toArray().map(arr=>arr.sort()).subscribe(x=>console.log(x))
like image 25
VincentGuo Avatar answered Oct 04 '22 21:10

VincentGuo