Hello! I understand the logic behind the solution. but for the ES6 syntax solution, I don’t understand why when we generate the sequential number between the range, we use _ for map prototype instead of min. Can anyone explain? Thanks.
function smallestCommons(arr) {
// Setup
const [min, max] = arr.sort((a, b) => a - b);
const range = Array(max - min + 1)
.fill(0)
.map((_, i) => i + min);
In this case, the _ is just a place holder. It is saying “I don’t care what this value is because I’m not going to use it but I need some variable name here so I can get to the second parameter”. That is not part of JS but is a convention that programmers sometimes use. (Be aware that there is also a popular library called lodash that is often accessed with _.)
So, that _ is just there so they can get to the index.
const [min, max] = arr.sort((a, b) => a - b);
… get my min and max …
const range = Array(max - min + 1)
… make me an array of the right size …
.fill(0)
… fill it with zeros … this is actually an important step, to fill it with something or the map won’t work properly …
.map((_, i) => i + min);
… map over those zeros, but I don’t care about those, just add the min to the index. Now, since the elements are all zeros, I guess they could have gone:
.map((num, i) => num + i + min);
but it doesn’t matter because they are all zero and so won’t affect the sum.