-1

Sorry if the title is confusing.

I have an object called question, which contains a property called brokenUp. I also have a randomly generated number. Now, if the number had 3 digits, I would want the program to add something. For instance:

var arr = [400, 40, 2]; //really just 442 but broken up.
var n= arr.length;

Now the main problem is here:

question.brokenUp = arr[0] + arr[1] + arr[2];

How can I make this line above work for any value?

What if I had 4 digits? How can I make it so it does arr[0]... arr[4] by itself and so on?

Edwin
  • 380
  • 1
  • 4
  • 18

1 Answers1

1

You could use reduce for this:

var arr = [1,2,3,4] // whatever length;

var brokenUp = arr.reduce(function(a, b) {return a + b;}, ''); // empty string here
omarjmh
  • 13,632
  • 6
  • 34
  • 42
  • Hey jordan, I'm not trying to combine the numbers, but rather to keep them separate. I'm using your brokenUp function and I want it to ask like 400 + 40 + 2 rather than 402, which your code does – Edwin Jun 06 '16 at 19:52
  • Oh I see, will edit – omarjmh Jun 06 '16 at 19:52
  • 1
    @Edwin: What else is `arr[0] + arr[1] + arr[2]` (the code from your question) if not a sum that combines the numbers? – Bergi Jun 06 '16 at 19:53
  • @Bergi, I didnt write this here, but in my actual code, I'm separating arr[0] with "+". Like this: question.brokenUp = question.n1 + "+" + arr[0] + "+" + arr[1]; – Edwin Jun 06 '16 at 19:54
  • You should have been clearer, check my edit... – omarjmh Jun 06 '16 at 19:55
  • 1
    @Edwin: Well you have to write what you're actually doing, otherwise we have no chance of answering what you want to know! You're looking for `arr.join(" + ")` btw. – Bergi Jun 06 '16 at 19:55
  • Yea, join is better here – omarjmh Jun 06 '16 at 19:56