# 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:

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿