w3resource

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

JavaScript Array: Exercise-36 with Solution

Pre-filled Numeric Array

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.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that creates an array of a specified length pre-filled with a given numeric value using Array.fill().
  • Write a JavaScript function that uses a for loop to generate an array of a fixed size with a default numeric value.
  • Write a JavaScript function that utilizes Array.from() to create a pre-filled numeric array of a specified length.
  • Write a JavaScript function that validates the length and default numeric value before creating the array.

Go to:


PREV : Random Array Item.
NEXT : Pre-filled String Array.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.