Documentación RxJS
  • Introducción
  • Operadores
    • Combinación
      • combineAll
      • combineLatest
      • concat
      • concatAll
      • exhaust
      • forkJoin
      • merge
      • mergeAll
      • race
      • startWith
      • switchAll
      • withLatestFrom
      • zip
    • Condicional
      • defaultIfEmpty
      • every
      • find
      • findIndex
      • isEmpty
      • sequenceEqual
    • Creación
      • ajax
      • defer
      • from
      • fromEvent
      • fromEventPattern
      • fromFetch
      • generate
      • iif
      • interval
      • of
      • range
      • throwError
      • timer
    • Gestión de Errores
      • catchError
      • retry
      • retryWhen
    • Filtración
      • audit
      • auditTime
      • debounce
      • debounceTime
      • distinct
      • distinctUntilChanged
      • distinctUntilKeyChanged
      • elementAt
      • filter
      • first
      • ignoreElements
      • last
      • sample
      • sampleTime
      • single
      • skip
      • skipLast
      • skipUntil
      • skipWhile
      • take
      • takeLast
      • takeUntil
      • takeWhile
      • throttle
      • throttleTime
    • Matemáticos y Agregación
      • count
      • max
      • min
      • reduce
    • Multidifusión
      • connect
      • multicast
      • publish
      • publishBehavior
      • publishLast
      • publishReplay
      • refCount
      • share
      • shareReplay
    • Transformación
      • buffer
      • bufferCount
      • bufferTime
      • bufferToggle
      • bufferWhen
      • concatMap
      • concatMapTo
      • exhaust
      • exhaustMap
      • expand
      • groupBy
      • map
      • mapTo
      • mergeMap
      • mergeMapTo
      • mergeScan
      • pairwise
      • partition
      • pluck
      • scan
      • switchMap
      • switchMapTo
      • window
      • windowCount
      • windowTime
      • windowToggle
      • windowWhen
    • Utilidad
      • delay
      • delayWhen
      • dematerialize
      • finalize
      • materialize
      • observeOn
      • repeat
      • repeatWhen
      • subscribeOn
      • tap
      • timeInterval
      • timeout
      • timeoutWith
      • timestamp
      • toArray
  • Conceptos
    • Observables
    • Observadores
    • Operadores
    • Schedulers
    • Sujetos
    • Suscripción
    • Testing de Canicas
  • API
    • Índice
      • ArgumentOutOfRangeError
      • bindCallback
      • bindNodeCallback
      • CompletionObserver
      • config
      • ConnectableObservable
      • EmptyError
      • ErrorObserver
      • FactoryOrValue
      • GroupedObservable
      • identity
      • InteropObservable
      • isObservable
      • MonoTypeOperatorFunction
      • NextObserver
      • noop
      • Notification
      • ObjectUnsubscribedError
      • observable
      • Observable
      • ObservableInput
      • ObservedValueOf
      • ObservedValuesFromArray
      • Observer
      • Operator
      • OperatorFunction
      • PartialObserver
      • pipe
      • scheduled
      • SchedulerAction
      • SchedulerLike
      • Subscribable
      • SubscribableOrPromise
      • Subscriber
      • Subscription
      • SubscriptionLike
      • TeardownLogic
      • TimeInterval
      • TimeoutError
      • Timestamp
      • UnaryFunction
      • Unsubscribable
      • UnsubscriptionError
      • VirtualTimeScheduler
    • ajax
      • AjaxError
      • AjaxRequest
      • AjaxResponse
      • AjaxTimeoutError
    • Schedulers
      • animationFrame
      • asap
      • async
      • queue
    • Sujetos
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
      • WebSocketSubject
    • webSocket
      • WebSocketSubjectConfig
    • Testing
  • Guías
    • Glosario
    • Importación
    • Instalación
    • Breaking Changes
      • Argumentos Array
      • Argumentos resultSelector
      • Argumentos scheduler
      • Argumentos subscribe
      • Conversión a Promesas
      • Multicasting
  • Sobre Nosotros
    • El Equipo
    • Código de Conducta
Powered by GitBook
On this page
  • Descripción
  • Ejemplos
  • Ejemplo de la documentación oficial
  • Recursos adicionales
  1. Operadores
  2. Condicional

findIndex

Emite el índice del primer valor emitido por el Observable fuente que cumple una determinada condición

PreviousfindNextisEmpty

Last updated 2 years ago

Signatura

Firma

findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean, thisArg?: any): OperatorFunction<T, number>

Parámetros

Retorna

OperatorFunction<T, number>: Un Observable del índice del primer elemento que cumpla la condición.

Descripción

Es como , pero emite el índice del valor encontrado, en lugar del propio valor.

findIndex busca el primer elemento del Observable fuente que cumpla la condición especificada en el predicado y retorna su índice (de base cero.) Al contrario que , el predicado es obligatorio en findIndex, y tampoco emite un error si no encuentra un valor válido.

Ejemplos

Emitir el índice del primer lenguaje de tipo Multiparadigma

import { findIndex } from "rxjs/operators";
import { from } from "rxjs";

const language$ = from([
  { name: "Java", type: "Orientado a objetos" },
  { name: "Ruby", type: "Multiparadigma" },
  { name: "Haskell", type: "Funcional" },
  { name: "Rust", type: "Multiparadigma" },
]);

language$
  .pipe(findIndex(({ type }) => type === "Multiparadigma"))
  .subscribe(console.log);
// Salida: 1

Emite el índice de la primera vez que se pulse la tecla x

import { findIndex, map } from "rxjs/operators";
import { fromEvent } from "rxjs";

const key$ = fromEvent<KeyboardEvent>(document, "keydown");

key$
  .pipe(
    map(({ code }) => code),
    findIndex((code) => code === "KeyX")
  )
  .subscribe(console.log);
// Salida: (Pulsar tecla n) (Pulsar tecla f) (Pulsar tecla x) 2

Ejemplo de la documentación oficial

Emite el índice del primer click que ocurre en un elemento DIV

import { fromEvent } from "rxjs";
import { findIndex } from "rxjs/operators";

const clicks = fromEvent(document, "click");
const result = clicks.pipe(findIndex((ev) => ev.target.tagName === "DIV"));
result.subscribe((x) => console.log(x));

Recursos adicionales

StackBlitz
Documentación oficial en inglés
find
first
StackBlitz
Source code
Diagrama de canicas del operador findIndex