2

I have the following code:

   if (this.places.length) {
    console.log(this.places);
    var myData = this.places.map(({ points }) => points);
    var myTotal = 0;  // Variable to hold your total

    for(var i = 0, len = myData.length; i < len; i++) {
        myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up
    }
    console.log(myTotal);
  }

I have an object see screenshot, from that object i need to extract all arrays, and from that arrays just a particular value, for example points.

The main goal is to sum and save all points into a new variable. The code from abobe it's not working.

1
  • would be good if you could put the source data, a sample... Commented Sep 1, 2019 at 21:41

2 Answers 2

5

If I understand correctly, you are wanting to calculate the total of all points fields in each Place object contanied in the this.places array and store the result in a new variable myTotal - one way to achieve that would be via reduce():

if (this.places.length) {

    /* The total returned by reduce() will be stored in myTotal */
    let myTotal = this.places.reduce((total, place) => {    

        /* For each place iterated, access the points field of the 
        current place being iterated and add that to the current
        running total */
        return total + place.points;

    }, 0); /* Total is initally zero */

    console.log(this.places);
    console.log(myTotal);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Another option could be to use the forEach on the places array and add the value of the points property:

   if (this.places.length) {
    var myTotal = 0;  // Variable to hold your total

    places.forEach(place => myTotal = myTotal + place.points);
    console.log(myTotal);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.