ntan
ntan

Reputation: 2205

sum contents of array and assign to another array

I have an array and I need to sum prices and assign to another array.

The problem is that

toll_prices[vehicle_id] = toll_prices[vehicle_id] + price;

is acting as a string because (I guess) the first time the toll_prices[vehicle_id] is undefined, and I don't get a number but a string undefined+1+2+3.

Here is the full code:

for (y in vehicles)  
{     
  var vehicle_id = vehicles[y].id;
  var price = vehicles[y].price;

  toll_prices[vehicle_id] = toll_prices[vehicle_id] + price;
} 

Any help appreciated

Upvotes: 0

Views: 38

Answers (2)

Daniel Beck
Daniel Beck

Reputation: 21505

The "convert a string to a number" is only part of the problem here.

tool_prices isn't an array; it's an object. Your existing code tries to perform addition on keys within tool_prices that aren't yet defined; that's where the "undefined" is coming from.

Here's an example that corrects this; see the comments in the code for details. (My use of forEach instead of your for...in is not significant, just habit; what's inside the loop is what matters.)

var vehicles = [
 { id: "a", price: "1"},
 { id: "a", price: "1"},
 { id: "a", price: "1"},
 { id: "a", price: "1"},
 { id: "b", price: "2"},
 { id: "c", price: "3"},
 { id: "d", price: "100"}
];
var tool_prices = {};

vehicles.forEach(function(v) {
  // need to define the tool_prices for this id if it doesn't exist yet:
  if (!tool_prices[v.id]) {
    tool_prices[v.id] = 0
  }
  // now we can add it (while also converting to Number, just to be sure):
  tool_prices[v.id] += Number(v.price);
});

console.log(tool_prices);

Update: now that I look at it again, I guess it's possible that tool_prices is a sparse array instead of an object, assuming the IDs are numeric. That doesn't change the core of the answer but here's an example of that for completeness:

var vehicles = [
 { id: 1, price: "1"},
 { id: 1, price: "1"},
 { id: 2, price: "1"},
 { id: 2, price: "1"},
 { id: 3, price: "2"},
 { id: 3, price: "3"},
 { id: 5, price: "100"}
];
var tool_prices = [];

// the rest is the same as in the above example
vehicles.forEach(function(v) {
  if (!tool_prices[v.id]) {
    tool_prices[v.id] = 0
  }
  tool_prices[v.id] += Number(v.price);
});

console.log(tool_prices);

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19525

You can use || 0 to turn any falsey value into the number 0, which will guarantee that you’re adding numbers, rather than undefined values:

toll_prices[vehicle_id] = (toll_prices[vehicle_id] || 0) + price;

Upvotes: 1

Related Questions