惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Fill an Array with Initial Values in JavaScript
Dmitri Pavlutin · 2021-10-19 · via Dmitri Pavlutin Blog

JavaScript provides many ways to initialize arrays with initial data. Let's see in this post which ways are the most simple and popular.

Table of Contents

  • 1. Fill an array with primitives
  • 2. Fill an array with objects
    • 2.1 Using array.fill()
    • 2.2 Using Array.from()
    • 2.3 Using array.map() with spread operator
  • 3. Conclusion

1. Fill an array with primitives

Let's say that you'd like to initialize an array of length 3 with zeros.

The array.fill(initalValue) method available on the array instance is a convenient way to initialize an arrays: when the method is called on an array, the entire array is filled with initialValue, and the modified array is returned.

But you need to use array.fill(initialValue) in combination with Array(n) (the array constructor):


const length = 3;

const filledArray = Array(length).fill(0);

filledArray; // [0, 0, 0]


Open the demo.

Array(length) creates a sparse array with the length of 3.

Then Array(length).fill(0) method fills the array with zeroes, returning the filled array: [0, 0, 0].

Array(length).fill(initialValue) is a convenient way to create arrays with a desired length and initialized with a primitive value (number, string, boolean).

2. Fill an array with objects

What if you need to fill an array with objects? This requirement is slightly nuanced depending if you want the array filled with the initial object instances, or different instances.

2.1 Using array.fill()

If you don't mind initializing the array with the same object instance, then you could easily use array.fill() method mentioned above:


const length = 3;

const filledArray = Array(length).fill({ value: 0 });

filledArray; // [{ value: 0 }, { value: 0 }, { value: 0 }]


Open the demo.

Array(length).fill({ value: 0 }) creates an array of length 3, and assigns to each item the { value: 0 } (note: same object instance).

This approach creates an array having the same object instance. If you happen to modify any item in the array, then each item in the array is affected:


const length = 3;

const filledArray = Array(length).fill({ value: 0 });

filledArray; // [{ value: 0 }, { value: 0 }, { value: 0 }]

filledArray[1].value = 3;

filledArray; // [{ value: 3 }, { value: 3 }, { value: 3 }]


Open the demo.

Altering the second item of the array filledArray[1].value = 3 alters all the items in the array.

2.2 Using Array.from()

In case if you want the array to fill with copies of the initial object, then you could use the Array.from() utility function.

Array.from(array, mapperFunction) accepts 2 arguments: an array (or generally an iterable), and a mapper function.

Array.from() invokes the mapperFunction upon each item of the array, pushes the result to a new array, and finally returns the newly mapped array.

Thus Array.from() method can easily create and initialize an array with different object instances:


const length = 3;

const filledArray = Array.from(Array(length), () => {

return { value: 0 };

});

filledArray; // [{ value: 0 }, { value: 0 }, { value: 0 }]


Open the demo.

Array.from() invokes the mapper function on each empty slot of the array and creates a new array with every value returned from the mapper function.

You get a filled array with different object instances because each mapper function call returns a new object instance.

If you'd modify any item in the array, then only that item would be affected, and the other ones remain unaffected:


const length = 3;

const filledArray = Array.from(Array(length), () => {

return { value: 0 };

});

filledArray; // [{ value: 0 }, { value: 0 }, { value: 0 }]

filledArray[1].value = 3;

filledArray; // [{ value: 0 }, { value: 3 }, { value: 0 }]


Open the demo.

filledArray[1].value = 3 modifies only the second item of the array.

2.3 Using array.map() with spread operator

You may be wondering: why use Array.from() and its mapper function, since the array has already an array.map() method?

Good question!

When using Array(length) to create array instances, it creates sparse arrays (i.e. with empty slots):


const length = 3;

const sparseArray = Array(length);

sparseArray; // [empty × 3]


And the problem is that array.map() skips the empty slots:


const length = 3;

const filledArray = Array(length).map(() => {

return { value: 0 };

});

filledArray; // [empty × 3]


Open the demo.

Thus using directly Array(length).map(mapperFunc) would create sparse arrays.

Fortunately, you can use the spread operator to transform a sparse array into an array with items initialized with undefined. Then apply array.map() method on that array:


const length = 3;

const filledArray = [...Array(length)].map(() => {

return { value: 0 };

});

filledArray; // [{ value: 0 }, { value: 0 }, { value: 0 }]


Open the demo.

The expression [...Array(length)] creates an array with items initialized as undefined. On such an array, array.map() can map to new object instances.

I prefer the Array.from() approach to filling an array with objects because it involves less magic.

3. Conclusion

JavaScript provides a bunch of good ways to fill an array with initial values.

If you'd like to create an array initialized with primitive values, then the best approach is Array(length).fill(initialValue).

To create an array initialized with object instances, and you don't care that each item would have the same object instance, then Array(length).fill(initialObject) is the way to go.

Otherwise, to fill an array with different object instances you could use Array.from(Array(length), mapper) or [...Array(length)].map(mapper), where mapper is a function that returns a new object instance on each call.

What other ways to fill an array in JavaScript do you know?