Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active July 12, 2019 14:43
Show Gist options
  • Save smitroshin/0ed3ad9870cd6651c4cc4070bd098761 to your computer and use it in GitHub Desktop.
Save smitroshin/0ed3ad9870cd6651c4cc4070bd098761 to your computer and use it in GitHub Desktop.
Fill array with one value 'n' times
// Fill array with value, len times
// Using concat
fillArray = (value, len) => {
if (len === 0) return [];
let a = [value];
while (a.length * 2 <= len) a = a.concat(a);
if (a.length < len) a = a.concat(a.slice(0, len - a.length));
return a;
};
// Fill array with value, len times
// Using push
fillArray = (value, len) => {
const arr = [];
for (let i = 0; i < len; i += 1) {
arr.push(value);
}
return arr;
};
// Fill array with value, len times
// Using spread operator
const fillArray = (value, len) => {
let arr = [];
for (let i = 0; i < len; i += 1) {
arr = [...arr, value];
}
return arr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment