2

Sorry for the tongue twister of a title but its a very specific problem.

Currently I have a array of objects being past through by props. I'm trying to sum up all the 'score' values together and display it in my app.

The object looks like this:

[{'id': '1', 'score': '10'}, {'id': '2', 'score': '20'}, {'id': '3', 'score': '35'}]

And inside the app it is being called as followed:

state = { 
     content: this.props.navigation.getParam('content', false),
}

scoreCount = () => {
    const content = this.state.content;

    if (content) {
        return content.reduce((prev, current) => prev.score + current.score);
    } else {
        return false;
}

render() {

const score = this.scoreCount()

return (
                <View>
                    <Text>Score:</Text>
                    { score ?
                        <Text>
                            { score }
                        </Text> :
                        <Text>
                            0
                        </Text>
                    }
                </View>
)}

It shows 'undefined35' on return

I know it has something to do with the props not being available on time of the call, but im not sure how to return it the score properly to the View

Any help would be very much appreciated

JronCh
  • 163
  • 1
  • 3
  • 11
  • 1
    What error is it giving? Those are strings btw, not numbers, so I don't think it will give the result you are expecting. – rrd Feb 25 '19 at 09:00
  • 1
    Possible duplicate of [javascript (+) sign concatenates instead of giving sum?](https://stackoverflow.com/questions/45840501/javascript-sign-concatenates-instead-of-giving-sum) and [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531) – adiga Feb 25 '19 at 09:12

1 Answers1

9

It seems you are trying to add the string because the value of score is '10' and so on which are string . So you can use unary operator to convert it to number. Secondly I think prev.score will be an issue during the first addition since there is no score key. So in the reduce a 0 being passed which will be considered as first element

let content = [{
  'id': '1',
  'score': '10'
}, {
  'id': '2',
  'score': '20'
}, {
  'id': '3',
  'score': '35'
}];

let sum = content.reduce(function(prev, current) {
  return prev + +current.score
}, 0);
console.log(sum)
brk
  • 48,835
  • 10
  • 56
  • 78