Create an array filled with given values Using JavaScript
Last Updated :
06 Feb, 2023
In JavaScript, an array is a collection of values that can be stored and accessed in a single variable. Each value in an array is called an element, and elements can be of any data type, such as numbers, strings, or other objects. Arrays are indexed, meaning that each element has a numerical position within the array. JavaScript arrays are dynamic, meaning that their size can be changed as needed. They are also zero-indexed, meaning that the first element is at position 0, the second element is at position 1, and so on.
You can create an array filled with given values using the following ways:
- Array fill method: This method is used to fill the array with a given static value.
- Array from method: This method is used to create a new array instance from a given array.
- Array.apply() method: This method is used to create an array filled with given values by passing actual parameters to the apply() method.
- Array spread Operator: It is used to expand an iterable (e.g. array, string, or object) into its individual elements.
- Array for loop method: It is used to Iterate every Individual element in the array.
Method 1: Using JavaScript Array Fill () function.
Approach:
- Declaring an array Given_values with a set of values using the var keyword.
- Creating a new array array using the Array() constructor and passing in an argument of 2 to create an array with 2 empty slots.
- Using the fill() method on the array to fill the empty slots with the Given_values array.
- Printing new array as output.
Example:
JavaScript
<script>
//declaring array with given values
var Given_values = [1, 2, 3, 4, 5];
console.log(`Given values array ${Given_values}`);
//creating an array filled with given values
var filledArray = Array(2).fill(Given_values);
//printing output array
console.log(`Array filled with given values is [${filledArray}]`);
</script>
Output
Given values array 1,2,3,4,5
Array filled with given values is [1,2,3,4,5,1,2,3,4,5]
Method 2: Using Array. From () method.
Approach: In this approach, we can create a new array instance from a given array using Array.from() method
Example:
JavaScript
<script>
//declaring array with Given values
var Given_values = [1, 2, 3, 4, 5];
console.log('Given values array '+Given_values);
//creating an array filled with Given_values array
var filledArray = Array.from({length: 1}, () => Given_values);
//printing output
console.log('Array filled with given values [ '+filledArray+' ]');
</script>
Output
Given values array 1,2,3,4,5
Array filled with given values is [1,2,3,4,5]
Method 3: Using Array.apply() method.
Array. apply() method is called on the Array object and it is passed two arguments:
Approach:
The first argument is null, which sets the value of this inside the function to null.
The second argument is Array (1), which creates an array of length 1.
Then. map(() => values) assigns the values array to each element of the new array. The map() method creates a new array with the results of calling a provided function on every element in the calling array. In this case, the provided function is an arrow function that returns the values array, so the new array is filled with 1 references to the same values array.
Example:
JavaScript
<script>
//declaring array with given values
var givenValues = [1, 2, 3, 4, 5];
console.log('Given elements:'+givenValues);
//create an array filled with given values
var filledArray = Array.apply(null, Array(1)).map((_,i) =>givenValues);
//printing output array
console.log('Array filled with given values [ '+filledArray+' ]');
</script>
Output:
Given values array 1,2,3,4,5
Array filled with given values is [1,2,3,4,5]
Method 4: Filling array using for loop.
Approach:
- initialize an empty array filledArray which will be used to store the values from the givenValues array.
- Declare given values into givenvalues array.
- Then, use for loop to iterate over the elements in the givenValues array.
- On each iteration, the current element is accessed using the index i and is pushed onto the filledArray using the Array.prototype.push() method.
- Finally, the results in the filledArray being filled with the same values as the givenValues array.
Example:
JavaScript
<script>
//declaring array with given values
var givenValues = [1, 2, 3, 4, 5];
console.log('Given elements:'+givenValues);
//declaring empty array
var filledArray = [];
//filling array using for loop
for (let i = 0; i < givenValues.length; i++)
{
filledArray.push(givenValues[i]);
}
//printing output array
console.log('Array filled with given values [ '+filledArray+' ]');
</script>
Output:
Given values array 1,2,3,4,5
Array filled with given values is [1,2,3,4,5]
Method 5: Filling array using spread syntax.
Approach: we will use the spread operator to copy the elements of the givenValues array into a new array. The spread operator allows you to take an iterable (such as an array) and expand its elements into a new array. By wrapping the givenValues array with the spread operator, it creates a new array with the same elements as the givenValues array.
Example:
JavaScript
<script>
//declaring array with given values
var givenValues = [1, 2, 3, 4, 5];
console.log('Given elements:'+givenValues);
//filling array using spread operator
var filledArray = [...givenValues];
//printing output array
console.log('Array filled with given values [ '+filledArray+' ]');
</script>
Output:
Given values array 1,2,3,4,5
Array filled with given values is [1,2,3,4,5]
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read