-3

In JavaScript/jQuery I'm generating value that can vary but is usually something like 0.12 or 0.25.

I want to generate an array that has a set amount of values (around 10 values or so) and include the number above at the start or end of the array. I want these values to decrease to 0 so for example -

var values = [0, 0.02, 0.04, 0.06, 0.08, 0.10, 0.12]

I'm just not quite sure how to acheive this.

Thanks

benji_croc
  • 44
  • 8

2 Answers2

0

You could likely solve this with Array.from:

function sequence(len, max) {
    return Array.from({length: len}, (v, k) => (k * max / (len - 1)).toFixed(2));
}

console.log(sequence(7, 0.12));
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • I added `toFixed(2)` in case the floating point issue was a problem for you, but it's quite possible you could remove that entirely. – cmbuckley Jan 10 '19 at 15:27
  • Thanks @cmbuckley I'm getting an issue/error with both v and k not being defined. I'm sure I'm being a dummy about it but just need some clarification – benji_croc Jan 10 '19 at 15:33
  • It's quite possible that's a JavaScript version issue. – cmbuckley Jan 10 '19 at 16:17
  • If you're running into problems with `Array.from`, it may be better to look at other implementations [here](https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp), or at [Create a JavaScript array containing 1…N](https://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n). underscore.js also has a [`_.range`](https://underscorejs.org/#range) function. – cmbuckley Jan 11 '19 at 10:31
0

An alternative approach could be creating a new array of the predefined length, and then use map() to fill the array with the expected values:

const createSeq = (len, val) =>
{
    return new Array(len).fill(0).map((x, i) => val / (len - 1) * i);
}

console.log(createSeq(7, 0.12));
console.log(createSeq(10, 0.25));
Shidersz
  • 16,846
  • 2
  • 23
  • 48