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

推荐订阅源

Hacker News - Newest:
Hacker News - Newest: "LLM"
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
SecWiki News
SecWiki News
N
News | PayPal Newsroom
T
Tor Project blog
W
WeLiveSecurity
A
Arctic Wolf
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
月光博客
月光博客
AWS News Blog
AWS News Blog
D
Docker
C
CERT Recently Published Vulnerability Notes
MyScale Blog
MyScale Blog
Google Online Security Blog
Google Online Security Blog
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
I
InfoQ
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
Recorded Future
Recorded Future
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
D
DataBreaches.Net
S
Security Affairs
WordPress大学
WordPress大学
T
Threatpost
Microsoft Security Blog
Microsoft Security Blog
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
S
SegmentFault 最新的问题
B
Blog RSS Feed
Project Zero
Project Zero
P
Proofpoint News Feed

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 How to Fill an Array with Initial Values 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 Handy Applications of JavaScript Array.from()
Dmitri Pavlutin · 2019-08-27 · via Dmitri Pavlutin Blog

Any programming language has functions that go beyond the basic usage. It happens thanks to a successful design and a wide area of problems it tries to solve.

One such function in JavaScript is the Array.from(): a workhorse allowing lots of useful transformations on JavaScript collections (arrays, array-like objects, iterables like string, maps, sets, etc).

In this post, I will describe 5 use cases of Array.from() that are both useful and interesting.

1. Quick introduction

Before starting, let's recall what Array.from() does. Here's how you would call the function:


Array.from(arrayLikeOrIterable[, mapFunction[, thisArg]]);


It's first obligatory argument arrayLikeOrIterable is an array-like object or an iterable.

The second optional argument mapFunction(item, index) {...} is a function invoked on every item in the collection. The returned value is inserted into the new collection.

Finally, the third optional argument thisArg is used as this value when invoking mapFunction. This argument is rarely used.

For examples, let's multiply by 2 the numbers of an array-like object:


const someNumbers = { '0': 10, '1': 15, length: 2 };

Array.from(someNumbers, value => value * 2); // => [20, 30]


2. Transform array-like into an array

The first useful application of Array.from() is indicated directly from its definition: transform an array-like object into an array.

Usually, you meet these strange creatures array-like objects as arguments special keyword inside of a function, or when working with DOM collections.

In the following example, let's sum the arguments of a function:


function sumArguments() {

return Array.from(arguments).reduce((sum, num) => sum + num);

}

sumArguments(1, 2, 3); // => 6


Array.from(arguments) transforms the array-like arguments into an array. The new array is reduced to the sum of its elements.

Moreover, you can use Array.from() with any object or primitive that implements the iterable protocol. Let's see a few examples:


Array.from('Hey'); // => ['H', 'e', 'y']

Array.from(new Set(['one', 'two'])); // => ['one', 'two']

const map = new Map();

map.set('one', 1)

map.set('two', 2);

Array.from(map); // => [['one', 1], ['two', 2]]


3. Clone an array

There is a tremendous number of ways to clone an array in JavaScript.

As you might expect, Array.from() easily shallow copies an array:


const numbers = [3, 6, 9];

const numbersCopy = Array.from(numbers);

numbers === numbersCopy; // => false


Array.from(numbers) creates a shallow copy of numbers array. The equality check numbers === numbersCopy is false, meaning that while having the same items, these are different array objects.

Is it possible to use Array.from() to create a clone of the array, including all the nested ones? Challenge accepted!


function recursiveClone(val) {

return Array.isArray(val) ? Array.from(val, recursiveClone) : val;

}

const numbers = [[0, 1, 2], ['one', 'two', 'three']];

const numbersClone = recursiveClone(numbers);

numbersClone; // => [[0, 1, 2], ['one', 'two', 'three']]

numbers[0] === numbersClone[0] // => false


recursiveClone() creates a deep clone of the supplied array. This is achieved by calling recursively recursiveClone() on array items that are arrays too.

Can you write a shorter than mine version of recursive clone that uses Array.from()? If so, please write a comment below!

4. Fill an array with values

In case if you need to initialize an array with the same values, Array.from() is at your service too.

Let's define a function that creates an array filled with the same default values:


const length = 3;

const init = 0;

const result = Array.from({ length }, () => init);

result; // => [0, 0, 0]


result contains a new array having 3 items initialized with zeros. This is done by invoking Array.from() with an array-like object { length }, and a map function that returns the initialization value.

However, there is an alternative method array.fill() that can be used to achieve the same result:


const length = 3;

const init = 0;

const result = Array(length).fill(init);

fillArray2(0, 3); // => [0, 0, 0]


fill() method fills the array correctly with initialization values, regardless of empty slots.

4.1 Fill an array with new objects

When every item of the initialized array should be a new object, Array.from() is a better solution:


const length = 3;

const resultA = Array.from({ length }, () => ({}));

const resultB = Array(length).fill({});

resultA; // => [{}, {}, {}]

resultB; // => [{}, {}, {}]

resultA[0] === resultA[1]; // => false

resultB[0] === resultB[1]; // => true


resultA created by Array.from() is initialized with different instances of empty objects {}. It happens because the map function () => ({}) on every invocation returns a new object.

However, resultB created by fill() method is initialized with the same instance of an empty object.

4.2 What about array.map()?

Is it possible to use array.map() method to achieve the same? Let's try that:


const length = 3;

const init = 0;

const result = Array(length).map(() => init);

result; // => [undefined, undefined, undefined]


The map() approach seems to be incorrect. Instead of the expected array with three zeros, an array with 3 empty slots is created.

It happens because Array(length) creates an array having 3 empty slots (also called sparse array), but map() method skips the iteration over these empty slots.

5. Generate ranges of numbers

You can use Array.from() to generate ranges of values. For example, the following function range generates an array with items starting 0 until end - 1:


function range(end) {

return Array.from({ length: end }, (_, index) => index);

}

range(4); // => [0, 1, 2, 3]


Inside range() function, Array.from() is supplied with the array-like { length: end }, and a map function that simply returns the current index. This way you can generate ranges of values.

6. Unique items of an array

A nice trick resulting from the ability of Array.from() to accept iterable objects is to quickly remove duplicates from an array. It is achieved in combination with Set data structure:


function unique(array) {

return Array.from(new Set(array));

}

unique([1, 1, 2, 3, 3]); // => [1, 2, 3]


At first, new Set(array) creates a set containing the items of the array. Internally, the set removes the duplicates.

Because the set is iterable, Array.from() extracts the unique items into a new array.

7. Conclusion

Array.from() static method accepts array-like objects, as well as iterables. It accepts a mapping function. Moreover, the function does not skip iteration over empty holes. This combination of features gives Array.from() a lot of possibilities.

As presented above, you can easily transform array-like objects to arrays, clone arrays, fill arrays with initial values, generates ranges and remove duplicated array items.

Indeed, Array.from() is a combination of good design, configuration flexibility allowing a wide area of collection transformations.

What other interesting use cases of Array.from() do you know? Please write a comment below!