Alaister Young
Alaister Young

Reputation: 357

Adding values from arrays in JavaScript

I am trying to add some values from objects inside of arrays together. Here is my example:

[
  {
    _id: "EnD2WbxhRJztDyfCA",
    day: "Saturday",
    totalMinutes: 10
  },
  {
    _id: "82NSKTYLiswWPbF8J",
    day: "Saturday",
    totalMinutes: 25
  }
]

I need to go into this array, grab out the totalMinutes values of both of them and then plus them together. Another problem I'm having is the number of objects within the array changes. So I can't do specific cases for the each different amount of objects.

Upvotes: 0

Views: 77

Answers (5)

anshulix
anshulix

Reputation: 197

arr.reduce has performance issues, I found this solution better if you have huge data rendering.

function getTotalMinutes(arr) {
  var result = 0;
  for (var i in arr){
    result += arr[i]['totalMinutes'];
  }
  return result;
}

Upvotes: 0

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

You need to parse the JSON first:

var arr = JSON.parse(myJson);

You can then reduce the array to a single value:

var value = arr.reduce(function (prev, curr) {
    return prev + curr.totalMinutes;
}, 0);

Upvotes: 0

Jigar
Jigar

Reputation: 44

You have the array into the JSON format. So first you need to convert it. You can do it as follows :-

var ele = jQuery.parseJSON( yourjson );

Then you can access each element as ele.time. This you can also perform in jQuery.each()

Hope this will help you.

Upvotes: 0

jtsnr
jtsnr

Reputation: 1210

Here is a function. You pass in the array and it returns the total minutes:

function getTotalMinutes(items) {
   var totalMinutes = 0;
   for (var i=0; i<items.length; i++) {
      var item = items[i];
      totalMinutes += item.totalMinutes;
    }

    return totalMinutes;
}

Upvotes: 3

Zumry Mohamed
Zumry Mohamed

Reputation: 9558

This might help you.

var arr = [
  {
    _id: "EnD2WbxhRJztDyfCA",
    day: "Saturday",
    totalMinutes: 10
  },
  {
    _id: "82NSKTYLiswWPbF8J",
    day: "Saturday",
    totalMinutes: 25
  }
];
var result = 0;

for (var x = 0; x < arr.length; x++ ){
  result += arr[x].totalMinutes 
}

console.log(result)

Upvotes: 0

Related Questions