Array.from () Five Super Useful Uses

  Front end, html5, javascript, node.js

Translation: Liu Xiaoxi

Original link:https://dmitripavlutin.com/ja …

Due to limited level, some translations in this article may not be accurate enough. If you have better ideas, please point them out in the comment area.

More articles to stamp: https://github.com/YvetteLau/ …

Any programming language has functions beyond basic usage, which benefits from successful design and attempts to solve a wide range of problems.

JavaScriptThere is one such function in:Array.from: allowed inJavaScriptCollection (e.g. array, class array object, or string,mapsetSuch as iteratable objects.

In this article, I will describe five useful and interesting onesArray.from()Use cases.

Introduction

Before we begin, let’s recallArray.from()The role of. Grammar:

Array.from(arrayLike[, mapFunction[, thisArg]])
  • ArrayLike: required parameter, pseudo array object or iterated object to be converted into array.
  • MapFunction: optional parameters,mapFunction(item,index){...}Is a function called on each item in the collection. The returned value will be inserted into the new collection.
  • ThisArg: optional parameter, execute callback functionmapFunctionThis object. This parameter is rarely used.

For example, let’s multiply each item of the class array by 2:

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

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

2. Convert the class array into an array

Array.from()The first purpose is to convert a class array object into an array.

In general, the class array objects you will encounter are: in the functionargumentsKeyword, or aDOMAssemble.

In the following example, let’s sum the parameters of the function:

function sumArguments() {
    return Array.from(arguments).reduce((sum, num) => sum + num);
}

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

Array.from(arguments)The class array objectargumentsConverts to an array, and then uses the of the arrayreduceMethods sum.

In addition,Array.from()The first parameter of can be any iterated object. Let’s continue to look at some 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

InJavaScriptThere are many ways to clone arrays in. As you might think,Array.from()It is easy to realize the shallow copy of the array.

const numbers = [3, 6, 9];
const numbersCopy = Array.from(numbers);

numbers === numbersCopy; // => false

Array.from(numbers)Created the rightnumbersA shallow copy of the array,numbers === numbersCopyThe result isfalse, which means that althoughnumbersAndnumbersCopyHas the same items, but they are different array objects.

Can I use itArray.from()Create a clone of the array, including all nested? Challenge!

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()Can be a deep copy of the array, by judging the array ofitemIs it an array, and if it is, continue to callrecursiveClone()To achieve a deep copy of the array.

Can you write a program that is better than usingArray.from()Recursive Copy A Shorter Array Deep Copy? If possible, please write it in the comment section below.

4. Fill the array with values

If you need to initialize the array with the same value, thenArray.from()It would be a good choice.

Let’s define a function and create an array filled with the same default values:

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

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

resultIs a new array, its length is 3, each item of the array is 0. callArray.from()Method, passing in a class array object{ length }And that returns the initialization valuemapFunctionFunction.

However, there is an alternativearray.fill()The same function can be realized.

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

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

fill()Fill the array correctly with the initial values.

4.1 Populating Arrays with Objects

When each item of the initialization 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

ByArray.fromReturnedresultAInitialize with different empty object instances. This happens because every time you call,mapFunction, that is, here() => ({})Will return a new object.

Then,fill()Method to create theresultBInitialize with the same empty object instance. Empty items will not be skipped.

4.2 Usearray.mapWhat about?

Can I use itarray.map()Methods to achieve? Let’s give it a try:

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

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

map()The method does not seem to be normal, and the array created is not expected.[0, 0, 0]But an array with 3 empty items.

This is becauseArray(length)An array with 3 empty items (also called sparse array) was created, butmap()Method skips empty items.

5. Generate a range of numbers

You can useArray.from()Generates a range of values. For example, the followingrangeFunction to generate an array from 0 toend - 1.

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

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

Inrange()In the function,Array.from()An array-like is provided{length:end}And a that simply returns the current indexmapFunction. This way you can generate a range of values.

6. Array de-duplication

Due toArray.from()The input of is an iterated object, so we can use it andSetCombining to achieve rapid deletion of duplicates from arrays.

function unique(array) {
  return Array.from(new Set(array));
}

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

First of all,new Set(array)A collection containing arrays was created.SetThe collection deletes duplicates.

Because ..SetThe collection is iterative, so you can use theArray.from()Converts it to a new array.

In this way, we can realize array de-duplication.

Conclusion

Array.from()The method accepts class array objects and iterated objects, which can accept amapFunction, and thismapFunction does not skip values ofundefinedThe numeric item of the. These characteristics giveArray.from()It offers many possibilities.

As mentioned above, you can easily convert a class array object into an array, clone an array, fill the array with initialization, generate a range, and realize array deduplication.

In fact,Array.from()Is a very good design, flexible configuration, allowing many sets of conversion.

You knowArray.from()Are there any other interesting use cases for? It can be written in the comment area.

Write at the end

It was one o’clock in the morning when the translation was finished. Sure enough, no adult’s life was easy.

Thank you for your friends’ willingness to spend precious time reading this article. If this article gives you some help or inspiration, please don’t be stingy with your praise and Star. Your affirmation is my greatest motivation to move forward.https://github.com/YvetteLau/ …

Recommend to pay attention to my public number:

clipboard.png