Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to fill array in sequence and add all the elements of the array

Today someone asked me that how will you create an array with N sequential elements like [1,2,3,...,N] (should start from 1), where N is provided by the user. For example, if N=10 then the array will be [1,2,3,4,5,6,7,8,9,10]. In addition, he wanted to sum the elements, so if N=10 then the result is 55.

I have done this as follows:

console.log(new Array(10).fill(1).map((x,y)=>x+y).reduce((x,y)=>x+y))
.as-console-wrapper { max-height: 100% !important; top: 0; }
.as-console-row{background: #000;color: #fff;}
.as-console-row-code{font-size:24px!important}

I just want to ask what is the best way to do the same problem and Why?

like image 536
Sourabh Somani Avatar asked Jan 20 '26 22:01

Sourabh Somani


2 Answers

If you are still looking for the "best" solution considering execution time, the following one is 55 times faster than the solution posted by Nina (https://jsfiddle.net/vc1wmk6e/):

function range (first, last) {
  var range = new Array(last - first + 1); range[0] = first;
  for (var i = 1; range[i - 1] < last; i++) range[i] = first + i;
  return range;
}

console.log(...range(1, 10));
console.log(range(1, 10).reduce((acc, x) => acc + x));

To know why it's (around 4.5 times) faster than fill + map, we need to look at the implementation of these two functions in order to calculate their time complexity. I'm not ready to dive into the JS source code right now, but there are chances that fill and map both iterate over the array elements. In this case the time complexity would be at least O(2N), while the range function is O(N). The remaining additional time may come from function calls that require lookups in memory to find the corresponding code, but this is a pure supposition :-|

You could create an array with Array.from by using an object with length as property and map the incremented indices.

var length = 10,
    array = Array.from({ length }, (_, i) => i + 1),
    sum = array.map((s => v => s += v)(0));

console.log(...array);
console.log(...sum);
like image 37
Nina Scholz Avatar answered Jan 22 '26 12:01

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!