DEV Community

Discussion on: 8 JavaScript Tips & Tricks That No One Teaches 🚀

Collapse
 
peerreynders profile image
peerreynders

Array.from is notable for its intended use of making Array-like data iterable with array methods, such as strings.

There's another case where it is extremely handy - creating a fresh array with elements initialized from a function.

const init = (_value, index) => (index + 1) * 3;
const length = 4;
const array = Array.from({ length }, init); // [3, 6, 9, 12]
for (let i = 0; i < length; i += 1) console.assert(array[i] === (i + 1) * 3);
Enter fullscreen mode Exit fullscreen mode

The issue with Array.prototype.fill() is that:

  • it requires an existing array (to modify)
  • it only places a single constant value into all the elements it replaces.

And Array.prototype.map() requires an already initialized array.

With Array.from() an array can be created and initialized with element content that varies by index in one fell swoop.

Collapse
 
lkarabeg profile image
lkarabeg

I kind of disagree, finding map much more readable.
Array.from({length: 4}).map((_value, index) => (index + 1) * 3)

Thread Thread
 
peerreynders profile image
peerreynders

With

const array = (new Array(length)).fill().map(init);
Enter fullscreen mode Exit fullscreen mode

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

const array = (new Array(length)).fill();
array.forEach((_v, i, a) => {
  a[i] = (i + 1) * 3;
});
Enter fullscreen mode Exit fullscreen mode

was 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 optional mapFn and thisArg parameters.

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);
Enter fullscreen mode Exit fullscreen mode

... but that's just me.

Some comments have been hidden by the post's author - find out more