Emits the single value at the specified index in a sequence of emissions from the source Observable.
Indexes are zero-based. The operator emits the i-th value, then completes. If the index is out of range and no default value is provided, it throws an ArgumentOutOfRangeError.
The number i for the i-th source emission that has happened since the subscription, starting from the number 0.Must be a non-negative integer. If negative, throws ArgumentOutOfRangeError immediately.
The default value returned for missing indices. If provided and the source completes before reaching the index, this value is emitted instead of throwing an error.
import { of, elementAt } from 'rxjs';const numbers = of(1, 2, 3);// Index existsnumbers.pipe(elementAt(1)).subscribe(console.log);// Output: 2// Index out of range, with defaultnumbers.pipe(elementAt(10, 'default')).subscribe(console.log);// Output: 'default'// Index out of range, without defaultnumbers.pipe(elementAt(10)).subscribe( value => console.log(value), err => console.error(err.message));// Output: ArgumentOutOfRangeError
import { from, elementAt } from 'rxjs';const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];const fruits$ = from(fruits);// Get the 3rd fruit (index 2)fruits$.pipe(elementAt(2)).subscribe(fruit => { console.log('Selected fruit:', fruit);});// Output: Selected fruit: cherry
Copy
Ask AI
import { interval, elementAt, switchMap } from 'rxjs';import { ajax } from 'rxjs/ajax';// Poll an API and get the 5th responseconst polling$ = interval(1000).pipe( switchMap(() => ajax.getJSON('/api/status')), elementAt(4) // 5th response (0-indexed));polling$.subscribe( status => console.log('5th status check:', status), err => console.error('Failed:', err));
import { interval, elementAt, skip, take } from 'rxjs';// These are equivalent:const withElementAt$ = interval(1000).pipe(elementAt(5));const withSkipTake$ = interval(1000).pipe(skip(5), take(1));// Both emit the 6th value (index 5)
import { of, elementAt, first, last, take, skip } from 'rxjs';const nums$ = of(1, 2, 3, 4, 5);// Get 3rd element (index 2)nums$.pipe(elementAt(2)).subscribe(console.log);// Output: 3// Get first elementnums$.pipe(first()).subscribe(console.log);// Output: 1// Get last element nums$.pipe(last()).subscribe(console.log);// Output: 5// Get 3rd element using skip + takenums$.pipe(skip(2), take(1)).subscribe(console.log);// Output: 3
import { range, elementAt } from 'rxjs';// elementAt still processes all values up to the indexconst million$ = range(1, 1000000).pipe( elementAt(999999));// The operator must count through 1 million emissions// Consider if there's a more efficient way to get your data