Translation: Liu Xiaoxi
The original link: dmitripavlutin.com/javascript-…
Due to the limited level, part of the translation may not be accurate, if you have a better idea, please point it out in the comments section.
More articles can be read: github.com/YvetteLau/B…
Any programming language has capabilities that go beyond basic usage, and it benefits from successful design and attempts to solve a wide range of problems.
There is one such function in JavaScript: array. from: allows useful conversions on JavaScript collections such as arrays, array-like objects, or iterable objects such as strings, maps, sets, etc.
In this article, I describe five useful and interesting array.from () use cases.
1. Introduction
Before we begin, let’s recall what array.from () does. Grammar:
Array.from(arrayLike[, mapFunction[, thisArg]])
Copy the code
- ArrayLike: Mandatory argument, pseudo array object or iterable that you want to convert to an array.
- MapFunction: Optional parameter,
MapFunction (item, index) {... }
Is a function called on each item in the collection. The returned value is inserted into the new collection. - ThisArg: Optional argument, executes callback function
mapFunction
Is this object. This parameter is rarely used.
For example, let’s multiply each item in the class array by 2:
const someNumbers = { '0': 10.'1': 15.length: 2 };
Array.from(someNumbers, value => value * 2); / / = > [20, 30]
Copy the code
2. Convert class arrays to arrays
Array.from() first use: to convert an array-like object into an Array.
In general, you’ll encounter array-like objects such as: the arguments keyword in a function, or a DOM collection.
In the following example, let’s sum the arguments to a function:
function sumArguments() {
return Array.from(arguments).reduce((sum, num) = > sum + num);
}
sumArguments(1.2.3); / / = > 6
Copy the code
Array.from(arguments) converts the array-like object arguments to an Array and sums it using the Array’s reduce method.
In addition, the first argument to array.from () can be any iterable, so let’s continue with some examples:
Array.from('Hey'); // => ['H', 'e', 'y']
Array.from(new Set(['one'.'two'])); // => ['one', 'two']
const map = new Map(a); map.set('one'.1)
map.set('two'.2);
Array.from(map); // => [['one', 1], ['two', 2]]
Copy the code
3. Clone an array
There are many ways to clone arrays in JavaScript. As you can imagine, array.from () makes it easy to make a shallow copy of an Array.
const numbers = [3.6.9];
const numbersCopy = Array.from(numbers);
numbers === numbersCopy; // => false
Copy the code
Array.from(numbers) Creates a shallow copy of the numbers Array. Numbers === numbersCopy Is false, meaning that although numbers and numbersCopy have the same entry, But they are different array objects.
Can I use array.from () to create a clone of an Array, including all nested ones? 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
Copy the code
RecursiveClone () performs a deep copy of an array by checking whether the item of the array is an array and then calling recursiveClone().
Can you write a shorter deep copy of an Array than using a recursive copy of array.from ()? If you can, please do so in the comment section below.
4. Populate the array with values
If you need to initialize an Array with the same value, array.from () is a good choice.
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]
Copy the code
Result is a new array with length 3 and each entry in the array is 0. Call array.from (), passing in an array-like object {length} and the mapFunction function that returns the initialization value.
However, there is an alternative method called array.fill() that does the same thing.
const length = 3;
const init = 0;
const result = Array(length).fill(init);
fillArray2(0.3); // => [0, 0, 0]
Copy the code
Fill () correctly fills the array with initial values.
4.1 Populating arrays with objects
Array.from() is a better solution when each item in the initialized Array should be a new object:
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
Copy the code
The resultA returned by array. from is initialized with different empty object instances. This happens because mapFunction, here () => ({}), returns a new object each time it is called.
The resultB created by the fill() method is then initialized with the same empty object instance. Empty items are not skipped.
4.2 the use ofarray.map
How’s that?
Can this be done using the array.map() method? Let’s try it:
const length = 3;
const init = 0;
const result = Array(length).map((a)= > init);
result; // => [undefined, undefined, undefined]
Copy the code
The map() method appears to be abnormal. Instead of creating the expected array [0, 0, 0], it creates an array with three empty entries.
This is because Array(Length) creates an Array with three empty items (also known as a sparse Array), but the map() method skips the empty items.
5. Generate numeric ranges
You can use array.from () to generate a range of values. For example, the following range function generates an array starting from 0 to end-1.
function range(end) {
return Array.from({ length: end }, (_, index) => index);
}
range(4); // => [0, 1, 2, 3]
Copy the code
In range(), array.from () provides an array-like {length: end}, as well as a map function that simply returns the current index. So you can generate ranges of values.
6. Array deduplication
Because array.from () is an iterable, we can use it in combination with Set to quickly remove duplicates from an Array.
function unique(array) {
return Array.from(new Set(array));
}
unique([1.1.2.3.3]); // => [1, 2, 3]
Copy the code
First, new Set(array) creates a collection of arrays, and the Set removes duplicates.
Because the Set collection is iterable, it can be converted to a new Array using array.from ().
In this way, we implement array de-duplication.
7. Conclusion
The array.from () method, which takes array-like objects as well as iterable objects, can accept a map function that does not skip numeric items whose value is undefined. These features give array.from () a lot of possibilities.
As mentioned above, you can easily convert an array-like object to an array, clone an array, populate the array with initialization, generate a range, and implement array de-duplication.
In fact, array.from () is a very nice design, flexible configuration, and allows for many collection conversions.
Do you know of any other interesting use cases for array.from ()? You can write in the comments section.
Write in the last
It’s one o ‘clock in the morning, and sure enough, no adult’s life is easy.
Thank you for your precious time reading this article. If this article gives you some help or inspiration, please do not spare your praise and Star. Your praise is definitely the biggest motivation for me to move forward.Github.com/YvetteLau/B…