DEV Community

Understanding Javascript Array Series II - Alternate ways of Creating an Array.

Nedy Udombat on September 30, 2019

In the first part of this series, I talked about what an array is and how to create an array here. Underst...
Collapse
 
akaustav profile image
Ameet Kaustav • Edited

Great article, @Nedy. Helped me understand the origins of some RxJS methods now. See RxJS.of and RxJS.from.

Found an issue though, which you might want to fix:

const arr3 = Array.from([1, 'nedy', undefined, null]);
// Seems to output [1, "nedy", undefined, null]
// instead of ["n", "e", "d", "y"]
Collapse
 
nedyudombat profile image
Nedy Udombat

Thanks a lot @akaustav , this must have been an oversight. I appreciate.

Collapse
 
benon_kityo profile image
Benon Kityo

Hi Nedy,thanks for the great article. Am a novice who is struggling with functions and would appreciate your help.
Var Repository =[
{
name:'Butterfree',
height:1.1,
types:['bug','flying']
},
{
name:'pidgey',
height:0.3,
types:['flying','normal']
},
{
name:'metapod',
height:0.5,
types:['bug']
}
];
repository.forEach(function(repository){
Please help me to write this repo using document.write

Collapse
 
seanmclem profile image
Seanmclem

Hey thanks. Just used array.fill and it worked perfectly

Collapse
 
nedyudombat profile image
Nedy Udombat

I am glad you found this useful, This has made my day @seanmclem .

Collapse
 
aphatheology profile image
Abdulkareem Mustopha

A newbie is confused...
Why is array().fill and array.of returning undefined for numbers?

Collapse
 
nedyudombat profile image
Nedy Udombat

Hi @aphatheology Array.fill() takes three arguments.

The first argument is the value you want to fill the array with, it can range from a string to an number to to even another array.

The second argument is the index of the array in which you want to start filling the array from. If you do this Array(5).fill(3, 2). This means you want to fill the array from index 2 till the end with the value if 3. This will return [undefined, undefined, 3, 3, 3]

The third argument is the index position of the array in which you want to stop filling the array. Array(5).fill(3, 2, 4) will give you this [undefined, undefined, 3, 3, undefined].

Array.of() doesn't return undefined for numbers.

Collapse
 
fiyiin profile image
Fiyiin

Great article @Nedy, showed me some array methods I didn't know of.

Collapse
 
nedyudombat profile image
Nedy Udombat

Thank you @fiyiin I am glad I could help.

Collapse
 
umoren profile image
Samuel Umoren

Wow
I just learnt about array.fill, array.of and array.from.
Awesome.

Collapse
 
nedyudombat profile image
Nedy Udombat

I am glad I could help @umoren .