Gostaria de saber se existe uma maneira conhecida, embutida / elegante de encontrar o primeiro elemento de uma matriz JS que corresponda a uma determinada condição. AC # equivalente seria List.Find .
Até agora, eu tenho usado uma combinação de duas funções como esta:
// Returns the first element of an array that satisfies given predicate
Array.prototype.findFirst = function (predicateCallback) {
if (typeof predicateCallback !== 'function') {
return undefined;
}
for (var i = 0; i < arr.length; i++) {
if (i in this && predicateCallback(this[i])) return this[i];
}
return undefined;
};
// Check if element is not undefined && not null
isNotNullNorUndefined = function (o) {
return (typeof (o) !== 'undefined' && o !== null);
};
E então eu posso usar:
var result = someArray.findFirst(isNotNullNorUndefined);
Mas como existem muitos métodos de matriz de estilo funcional no ECMAScript , talvez já exista algo como esse? Eu imagino que muitas pessoas precisam implementar coisas assim o tempo todo ...
return (typeof (o) !== 'undefined' && o !== null);
até isso return o != null;
. Eles são exatamente equivalentes.