Create a generic array in JavaScript
This post will discuss how to create a generic array in JavaScript.
There are several ways to create a generic array in JavaScript. A generic array is an array that can store any type of data, such as numbers, strings, booleans, objects, or other arrays. Here are some of the functions that we can use to create a generic array in JavaScript:
1. Using Array Literal
We can use an array literal, which is a pair of square brackets with comma-separated values inside. This is the simplest and most common way to create an array in JavaScript. Here’s an example:
|
1 2 3 4 5 |
// a generic array with different types of data let arr = [1, "hello", true, {name: "Anne"}, [2, 3, 4]]; // [ 1, 'hello', true, { name: 'Anne' }, [ 2, 3, 4 ] ] console.log(arr); |
2. Using Array constructor
We can use the Array constructor, which is a function that creates a new array object. We can pass one or more arguments to the constructor to specify the elements or the length of the array. Here’s an example:
|
1 2 3 4 5 |
// a generic array with different types of data let arr = new Array(1, "hello", true, {name: "Anne"}, [2, 3, 4]); // [ 1, 'hello', true, { name: 'Anne' }, [ 2, 3, 4 ] ] console.log(arr); |
3. Using Array.from() function
We can use the Array.from() function, which creates a new array from an iterable or an array-like object. An iterable is an object that can be looped over, such as a string or a set. An array-like object is an object that has a length property and indexed elements, such as a NodeList or an arguments object. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 |
// a generic array with the characters of the string let arr1 = Array.from("hello"); console.log(arr1); // [ 'h', 'e', 'l', 'l', 'o' ] // a generic array with the values of the set let arr2 = Array.from(new Set([1, 2, 3])); console.log(arr2); // [ 1, 2, 3 ] // a generic array with the elements of the array-like object let arr3 = Array.from({length: 5, 0: "a", 1: "b", 2: "c"}); console.log(arr3); // [ 'a', 'b', 'c', undefined, undefined ] |
These are some of the ways to create a generic array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)