Home > Enterprise >  Get the sum total of a value from flatlist react native
Get the sum total of a value from flatlist react native

Time:10-26

I am trying to get the sum total of all the value retrieve from my fetch in a FlatList below is my code.

<SafeAreaView style={styles.container}>
    <FlatList
        data={numList}
        listKey="number-list"
        keyExtractor={item => item.id}
        renderItem={({ item }) => {
            return (
                <View style={styles.ticSec}>
                    <Text>{item.amount}</Text>
                </View>
            )
        }}
    />
</SafeAreaView> 

The Output result:

10
20
15

How can I make it output sum total of of 45 whick is the sometotal of 10,20,15

thank you for you help

CodePudding user response:

User Array.prototype.reduce to calculate the sum of the amounts of all items in your numList like so:

const sumTotal = numList.reduce((acc, next) => {
  return acc   next.amount
}, 0)

where acc stands for accumulator and next is the next item we iterate over.

you can then use the value in your jsx:

<Text>{sumTotal}</Text>

More about reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  • Related