I kind of disagree, finding map much more readable. Array.from({length: 4}).map((_value, index) => (index + 1) * 3)
With
const array = (new Array(length)).fill().map(init);
it always ground my gears that to arrive at the desired array another disposable array had to be created and "filled" just to convey that I want length elements. And
length
const array = (new Array(length)).fill(); array.forEach((_v, i, a) => { a[i] = (i + 1) * 3; });
was clunky enough to make me want to use a for loop.
for
So if I'm are already using Array.from() I might as well use the optional mapFn and thisArg parameters.
Array.from()
mapFn
thisArg
function init(_value, index) { return (index + 1) * this.factor; } const config = { length: 4 }; const two = { factor: 2 }; const three = { factor: 3 }; const array2 = Array.from(config, init, two); const array3 = Array.from(config, init, three); const checkArray = (expected, actual) => { const actualMatches = (value, index) => value === actual[index]; console.assert( expected.length === actual.length && expected.every(actualMatches), 'array mismatch - expected: %o actual: %o', expected, actual ); }; const TWOS = [2, 4, 6, 8]; const THREES = [3, 6, 9, 12]; checkArray(TWOS, array2); checkArray(THREES, array3);
... but that's just me.
Some comments have been hidden by the post's author - find out more
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I kind of disagree, finding map much more readable.
Array.from({length: 4}).map((_value, index) => (index + 1) * 3)
With
it always ground my gears that to arrive at the desired array another disposable array had to be created and "filled" just to convey that I want
length
elements. Andwas clunky enough to make me want to use a
for
loop.So if I'm are already using
Array.from()
I might as well use the optionalmapFn
andthisArg
parameters.... but that's just me.