Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
¿Cómo restar dos valores de matriz (de diferentes claves) usando una tubería ramda?

En una tubería ramda , quiero restar los valores de dos claves de matriz, para finalmente terminar con una matriz de esas diferencias.

Por ejemplo, considere la siguiente matriz mice_weights . Quiero obtener una matriz con las diferencias weight_post menos weight_pre , solo para ratones macho.

 const mice_weights = [ { "id": "a", "weight_pre": 20, "weight_post": 12, "is_male": true }, { "id": "b", "weight_pre": 25, "weight_post": 19, "is_male": false }, { "id": "c", "weight_pre": 15, "weight_post": 10, "is_male": true }, { "id": "d", "weight_pre": 30, "weight_post": 21, "is_male": false } ]

Entonces, según esta respuesta , puedo construir 2 conductos equivalentes, get_pre() y get_post() :

 const R = require("ramda"); filter_males = R.filter(R.path(["is_male"])) // my filtering function const get_pre = R.pipe( filter_males, R.map(R.prop("weight_pre")) ) const get_post = R.pipe( filter_males, R.map(R.prop("weight_post")) ) res_pre = get_pre(mice_weights) // [20, 15] res_post = get_post(mice_weights) // [12, 10] const res_diff = res_pre.map((item, index) => item - res_post[index]) // taken from: https://stackoverflow.com/a/45342187/6105259 console.log(res_diff); // [8, 5]

Aunque [8, 5] es el resultado esperado, me pregunto si hay una forma más corta de usar la tubería de ramda como:

 // pseudo-code const get_diff = R.pipe( filter_males, R.subtract("weight_pre", "weight_post") ) get_diff(mice_weights) // gives [8, 5]

¿Es posible lograr algo similar usando ramda ? ¿Quizás hay una funcionalidad integrada para tal tarea?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Para obtener una diferencia de peso en un solo objeto, cree una función usando R.pipe que tome los valores de props relevantes con R.props y los aplique a R.subtract .

Ahora puede crear una función que filtre los elementos y mapee los objetos usando la función de cálculo de peso:

 const { pipe, props, apply, subtract, filter, prop, map, } = R const calcWeightDiff = pipe( props(['weight_pre', 'weight_post']), apply(subtract) ) const fn = pipe( filter(prop('is_male')), map(calcWeightDiff) ) const mice_weights = [{"id":"a","weight_pre":20,"weight_post":12,"is_male":true},{"id":"b","weight_pre":25,"weight_post":19,"is_male":false},{"id":"c","weight_pre":15,"weight_post":10,"is_male":true},{"id":"d","weight_pre":30,"weight_post":21,"is_male":false}] const result = fn(mice_weights) console.log(result) // gives [8, 5]
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Lo siento, no sé sobre ramda pipes, pero esto es un asunto trivial para el mapeo y el filtrado de matrices.

 const get_diff = (n, v) => // this takes a field and value to filter mice_weights .filter(f => f[n] === v) // this keeps only datasets that have the field/value combo you're seeking .map(f => f.weight_pre - f.weight_post) // this gets the diff 

 const mice_weights = [{ "id": "a", "weight_pre": 20, "weight_post": 12, "is_male": true }, { "id": "b", "weight_pre": 25, "weight_post": 19, "is_male": false }, { "id": "c", "weight_pre": 15, "weight_post": 10, "is_male": true }, { "id": "d", "weight_pre": 30, "weight_post": 21, "is_male": false } ] const get_diff = (n, v) => mice_weights.filter(f => f[n] === v).map(f => f.weight_pre - f.weight_post) console.log(get_diff('is_male', true)) // gives [8, 5]

about 4 years ago · Juan Pablo Isaza Denunciar

0

Propondría usar props y funciones reduceRight para lograr eso:

 const getProps = R.props(['weight_pre', 'weight_post']) const subtract = R.reduceRight(R.subtract)(0) const get_diff = R.pipe( R.filter(R.path(['is_male'])), R.map(R.pipe(getProps, subtract)) ) console.log(get_diff(mice_weights));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda