w3resource

JavaScript: Create a specified number of elements and pre-filled numeric value array

JavaScript Array: Exercise-36 with Solution

Write a JavaScript function to create a specified number of elements with a pre-filled numeric value array.

Test Data:
console.log(array_filled(6, 0));
[0, 0, 0, 0, 0, 0]
console.log(array_filled(4, 11));
[11, 11, 11, 11]

Sample Solution:

JavaScript Code:

// Function to create a new array with 'n' elements, each initialized to the specified 'val'
function array_filled(n, val) {
    // Use Array.apply to create an array-like object with 'n' undefined elements
    // and then use map to fill each element with the specified 'val'
    return Array.apply(null, Array(n)).map(Number.prototype.valueOf, val);
}

// Output the result of array_filled with 'n=6' and 'val=0'
console.log(array_filled(6, 0));

// Output the result of array_filled with 'n=4' and 'val=11'
console.log(array_filled(4, 11));

Output:

[0,0,0,0,0,0]
[11,11,11,11]

Flowchart:

Flowchart: JavaScript: Create a specified number of elements and pre-filled numeric value array

ES6 Version:

// Function to create a new array with 'n' elements, each initialized to the specified 'val'
const array_filled = (n, val) => Array.from({ length: n }, () => val);

// Output the result of array_filled with 'n=6' and 'val=0'
console.log(array_filled(6, 0));

// Output the result of array_filled with 'n=4' and 'val=11'
console.log(array_filled(4, 11));

Live Demo:

See the Pen JavaScript - Create a specified number of elements and pre-filled numeric value array-array-ex- 36 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to get a random item from an array.
Next: Write a JavaScript function to create a specified number of elements and pre-filled string value array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-array-exercise-36.php