preface

I wanted to do this series last year when I discovered that the replace method of string has many magical uses, but I didn’t have time and didn’t have a good name, so I shelved it. Last Friday, when I read the comments, one solution was to use Array. From one line to solve the problem, and the efficiency is quite high. I nibbled through the documentation and the blog, figured it out and thought it was a good time to start the series. And arrays are one of the most commonly used data structures in our development. As one of the methods to generate arrays, it makes sense to start with from. Let’s just call it that for now.

Basic grammar

Definition: The from() method is used to return an array from an object with a length attribute or an iterable object.

Syntax: array. from(object, mapFunction, thisValue)

parameter describe
object
Required, object to be converted to array.
mapFunction
Optionally, the function to call for each element in the array.
thisValue
Optionally, map this object in mapFunction.

Sample usage

1. Convert class arrays to arrays

Array.from('hello') //["h", "e", "l", "l", "o"] Array.from(new Set(['name','age'])) //["name", "age"] Array.from({name:'lgc',age:25}) //[] let map=new Map() map.set('name','lgc') map.set('age',25) Array.from(map) / / [[" name ", "LGC"], [25] "age",] the function test () {the console. The log (Array) from (the arguments)} the test (1, 2, 3) / / [1, 2, 3]Copy the code

While writing these examples, I wondered why a Map could be converted to an array while an Object could only be converted to an empty array. I didn’t understand until I looked at the rookie tutorial and saw the above definition. Object has no length and is not an iterable. I used to think that object is also an iterable. After all, you can use for-in. In fact, es6 object is not an iterable, so I won’t go into details here. If you are interested, you can look it up.

2. Array deep copy (one line of code)

function clone(arr){ return Array.isArray(arr) ? Array.from(arr, Clone):arr} let arrayA=[[1,2],[3,4]] let arrayB=clone(arrayA) arrayA===arrayB //false arrayA[0]===arrayB[0] //falseCopy the code

By default, mapFunction passes two parameters, the value of the Array and the index.

3. Array deduplication

function unique(arr){
    return Array.from(new Set(arr))
}
Copy the code

This is also the most basic and one of the most commonly used functions of FROM.

4. from

The from definition again: The from() method is used to return an array from an object with a length attribute or an iterable object. Just have Length, right? Give it a try

Array. The from ({2} length:, (val, index) = > index) / / [0, 1]Copy the code

Yeah, well, what good is he for? First, like the code above, it is very easy to generate arrays with certain rules in a certain range

Array. The from ({length: 3}, (val, index) = > index * 10) / /,10,20 [0]Copy the code

Second, initialization of the array. Say you want to generate an array of objects of specified length. What was the first reaction? The fill?

let testArr=Array(3).fill({})
testArr[0]===testArr[1]                                         //true
Copy the code

Every object here is essentially the same, and if you change one the others will follow, but a lot of times that’s not what we want.

let testArrb=Array.from({length:3},()=>({}))
testArrb[0]===testArrb[1]                                       //false
Copy the code

These two methods can be used as required.

5

The above content is actually layer by layer down in order to better understand the following way of thinking.

LeetCode第867:

Given A matrix A, return the transpose of A.

The transpose of a matrix is to reverse the main diagonal of the matrix and swap the row index and column index of the matrix.

Example 1: input: [[1, 2, 3], [4 and 6], [7,8,9]] output: [,4,7 [1], [2,5,8], [3,6,9]] example 2: input: [[1, 2, 3], [4 and 6]] output: [[1, 4], [2, 5], [3]]

The first thought was that it wasn’t an index swap? The thief is simple. So I wrote the following code

var transpose = function(A) { let x=A.length let y=A[0].length for(let i=0; i<x; i++){ for(let j=0; j<y; j++){ if(j-i>0){ [A[i][j],A[j][i]]=[A[j][i],A[i][j]] } } } return A };Copy the code

Execute code: pass, submit: fail. Oh my god? When you look at the error message, you see that the “length and width” are unequal, as in example 2. Change ideas, inside and outside circulation. Each time the outermost loop is executed, one column is treated as a row. Execute, pass.

var transpose = function(A) { let x=A.length let y=A[0].length let B=[] for(let i=0; i<y; i++){ let cache=[] for(let j=0; j<x; j++){ cache.push(A[j][i]) } B.push(cache) } return B };Copy the code

However, this version looks too fun and takes too long to implement. But you’ve done it yourself, so look for other ideas in the comments section.

This is to see the comments section of god implementation, the first time did not understand.

var transpose = function(A) {
    return Array.from({length:A[0].length},(_v,i)=>A.map(v=>v[i]))
};
Copy the code

{length:A[0].length}, takes the width of the given matrix as the length of the transpose matrix, in order to satisfy the condition “object with length attribute”. (_v, I)=> a.map(v=>v[I]), take the columns of the given matrix as the rows of the transpose matrix. The core idea and my second edition is the same, but the implementation of the way and skills show too much. And the execution time is also short, worship god.