Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

189
Vistas
React Native moment.js find sum of elements which fall in a date range otherwise return 0

Im working with react native chart kit, I want to be able to display a graph of spending in my react native app. I'm using moment.js and moment-range

calendar.forEach((range) => {
    const label = range.start.format('DD MMM')
    loaded.labels.push(label);

    const filtered = spendingData
        .filter(item => range.contains(moment(item.timestamp)))
        .reduce((a,b) => (a.spent || 0) + (b.spent || 0), 0);
    
        loaded.data.push(filtered);
});

setGraph({...graph, labels: loaded.labels, data: loaded.data});

The filter by its self returns the correct items, each time one or more objects fall within the range it should be then passed to the reduce function to add them.

Objects returned without reduce (dates with nothing under means that there where no spendings that day) this works fine:


26 Dec
---------
02 Jan
---------
09 Jan
---------
16 Jan

Object {
  "spent": 3.8,
  "timestamp": 1642713860026,
}

Object {
  "spent": 12,
  "timestamp": 1642714020254,
}

---------
23 Jan
---------
30 Jan

Object {
  "spent": 2.4,
  "timestamp": 1643582338356,
}

Object {
  "spent": 5.5,
  "timestamp": 1643582748421,
}

Data returned after reducing the item.spent values, this is where the problem lies:

0

0

0

12

0

5.5
7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos