Skip to content

map

Transforms each value emitted by the source using a mapping function that also receives the emission index.

Timeline of observable eventsABC
map((x, i) => `${i}: ${x}`)
Timeline of observable events0: A1: B2: C
// Timeline:
//
// num$ "A" "B" "C"
// indexed$ "0: A" "1: B" "2: C"
//
// Explanation:
// - mapWithIndex transforms each value along with its index
// - Index starts at 0 and increments with each emission
const num$ = source<string>();
const indexed$ = num$.pipe(map((x, i) => `${i}: ${x}`));
const valueHistory: string[] = [];
indexed$.subscribe((s) => {
valueHistory.push(s);
});
num$.next('A'); // 0: A
num$.next('B'); // 1: B
num$.next('C'); // 2: C
assert.deepStrictEqual(valueHistory, ['0: A', '1: B', '2: C']);

View source on GitHub