Estoy buscando una manera de reducir/filtrar una matriz en función de un valor. Así por ejemplo:
Tengo una matriz: _postInsightSizeOptions: number[] = [5, 10, 25, 50, 100];
Por ejemplo:
Input = 6 - the new array (_postInsightSizeOptionsFiltered) should only output [5, 10] Input = 5 - the new array (_postInsightSizeOptionsFiltered) should only output [5] Input = 28 - the new array (_postInsightSizeOptionsFiltered) should only output [5, 10, 25, 50] Mi intento: this._postInsightSizeOptionsFiltered = this._postInsightSizeOptions.filter(size => size <= 7); pero esto solo genera [5] en lugar de [5, 10]
Puede tomar todos los valores más pequeños y el siguiente valor mayor si el valor deseado no existe.
const filter = (array, value) => array.filter((v, i, a) => v <= value || a[i - 1] < value), data = [5, 10, 25, 50, 100]; console.log(...filter(data, 6)); // [5, 10] console.log(...filter(data, 5)); // [5] console.log(...filter(data, 28)); // [5, 10, 25, 50]Esta respuesta intenta manejar explícitamente los casos extremos (es decir, un número inferior al tamaño de página más bajo, es decir, menos de 5 ). Devuelve una cadena "no pages" , pero podría adaptarse para devolver algo más apropiado según el contexto.
Fragmento de código
const customFilter = (arr, num) => ( num < arr[0] ? ['no pages'] : arr.filter((pgSz, idx) => { if (pgSz <= num) return true; // if array-elt less than or equals "num" if (idx > 0) { // for 2nd & subsequent array-elements // if prev array-elt was less than "num" // AND current array-elt greater than "num" if (arr[idx-1] < num && num < pgSz) return true; }; }) ); const data = [5, 10, 25, 50, 100]; console.log('case 1: ', ...customFilter(data, 6)); // [5, 10] console.log('case 2: ', ...customFilter(data, 5)); // [5] console.log('case 3: ', ...customFilter(data, 28)); // [5, 10, 25, 50] console.log('case 4: ', ...customFilter(data, 4)); // [?] console.log('case 5: ', ...customFilter(data, 105)); // [?]Explicación
Comentarios en línea agregados en el fragmento anterior.