DEV Community

Cover image for Different ways of structuring Arrays in Javascript
JeffUbayi
JeffUbayi

Posted on

Different ways of structuring Arrays in Javascript

Arrays are indispensable data-structures in javascript and understanding how to effectively use them to solve problems is a crucial skill to master.

We will be taking a look into some of the many ways to create Arrays in Javascript.


Table of Contents:


I'll be using the Avengers Comic flick just to make learning fun while creating an array of Superheros.

Lets "Assemble the Avengers".

What is an Array

An array data structure or an array is an ordered list of values, or a collection of elements (values or variables) identified by an index or key. The most simple type of array data structure is a linear array.

Basic way

At first, the basic way to create arrays is here as follows:

const Avengers = ['Ironman', 'Hulk', 'Thor', 'Cpt America'];

With Array Constructor

Another way to create array is by using Array Constructor function.

const Avengers = new Array('Hulk', 'Thor', 'Ironman', 'Cpt America');

You can achieve same with new Array function of. Like in the following example for Array.of , we create array of mixed values:

const Avengers = Array.of('Hulk', null, 'Thor', undefined);
console.log(Avengers);
// πŸ‘† (4) ["Hulk", null, "Thor", undefined]

Interesting thing to notice about the Constructor function is its handy override. The override is that if you pass only one argument and it is an integer, the Constructor function will create an empty array for you of that specified length.


Spread Operator

It spreads the items that are contained in an iterable (an iterable is anything that can be looped over, like Arrays, Sets…) inside a receiver (A receiver is something that receives the spread values)

Like in the following example, we will add the new item and spread the old array to create a complete new Array.

const moreAvengers = ['Cpt Marvel', ...Avengers ];

From another Array

Array.from will allow you to create the Arrays from another array.

The newly created array is completely new copyrights and is not gonna mutate any changes to the old array.

const Avengers = new Array('Hulk', 'Thor', 'Cpt America', 'Ironman');
const copyOfAvengers = Array.from(Avengers);

From Array-Like Objects

Some Lists look like Arrays but are not arrays. And, at that time you might wanna convert it to Array to better operability and readability on the data structure.

One of such list is NodeList which you receive as an output of document.querySelectorAll

const divs = document.querySelectorAll('div');
const divsArray = Array.prototype.slice.call(divs);

Here you can use the Array.from function as well to create the array from the Array-like objects. Let’s see that in the following example:

const divs = document.querySelectorAll('div');
const divsArray = Array.from(divs);

Using Loops like Map and Reduce

Event though map and reduce are used to loop over the Arrays. Their non-mutating nature allows us to create new Arrays in different ways.

Array Map

Map function will loop over items and return a new array of mapped Items

const Avengers = ['Hulk', 'Thor', 'Ironman', 'Cpt Amrica'];

const avengersEndgame = Avengers.map(a => `${a} kills Thanos`);

console.log(avengersEndgame);

// πŸ‘† (4) ["Hulk kills Thanos", "Thor kills Thanos", "Ironman kills Thanos", "Cpt America kills Thanos"]

Array Reduce

Reduce will allow you to loop over the items and do any kind of operation related to the item. The outputs of those operations can be added to any kind of collection, and here, a new Array.

const avengers = ['Ironman', 'Hulk', 'Thor', 'cpt America'];
const avengersCopy = avengers.reduce((gang, avengers) => [
  ...gang,
  { avengers }
], []);
console.log(avengersCopy);
/* πŸ‘† 
    .    (4) [{…}, {…}, {…}, {…}]
    .    0: {avenger: "Hulk"}
    .    1: {avenger: "Thor"}
    .    2: {avenger: "Cpt America"}
    .    3: {avenger: "Ironman"}
    .    length: 4
*/

New Array of Length and Fill with some value

We can quickly create new Arrays of any finite length with Array constructor.

All we have to do is to pass that indefinite length of the desired array as a number to the constructor.

Like in the following example, we will create a new Array of length 6.

Though creating an empty array is useless because you will not be able to use the Array functions until it has items in it.

One quick way to do so is to use the .fill method of the array and put an arbitrary value in each index of the Array.

Once the array is Filled, you can use the loops to enhance it more with the different values.

const emojis = new Array( 6 ).fill( '😎' );
console.log(emojis);
// πŸ‘† (6) ["😎", "😎", "😎", "😎", "😎", "😎"]

// Breakdown: 
const arr = new Array( 6 );
console.log(arr);
/* πŸ‘†
    .    (6) [empty Γ— 6]
    .    length: 6
*/
arr.fill( Math.random().toFixed(2) );
/* πŸ‘†
    .    (6) ["0.80", "0.80", "0.80", "0.80", "0.80", "0.80"]
    .    0: "0.80"
    .    1: "0.80"
    .    2: "0.80"
    .    3: "0.80"
    .    4: "0.80"
    .    5: "0.80"
    .    length: 6
*/

Form Objects using Object.keys and Object.values

You can create array of Keys or Values of any Object with functions Object.keys and Object.values respectively.

const avengers = {
  1: 'Black Panther',
  2: 'Ironman',
  3: 'Cpt America',
  4: 'Thor',
  5: 'Hulk',
  6: 'Cpt Marvel',
  7: 'Antman'

Array Concat Function

You can use the Array Concat function to create new Arrays as well.

If you use an empty array as the starting point, the output of [].concat will be a new copy of concatenated Arrays.

const Avenger = ['Hulk'];
const moreAvengers = [].concat(Avenger, 'Thor', ['Ironman']);
console.log(moreAvengers);
// (3) ["Hulk", "Thor", "Ironman"]

Conclusion

As we have seen some different ways to create Arrays in JavaScript.

Not all of these methods can be used in same ways and every methods has its perk for specific use cases.

Top comments (0)