Li cloud double 12 again, low to1 fold, really feel very cost-effective, you can click on this content directly to participate

1. Powerful Reduce

The reduce method of arrays is very versatile. It is typically used to reduce each item in an array to a single value. But you can do so much more with it.

1.1 Using Reduce to Implement Map and Filter

Suppose you have a sequence, and you want to update each of its entries (map functionality) and filter out some of them (filter functionality). If you use map and filter first, you need to traverse the array twice.

In the code below, we double the values in the sequence and pick out the numbers greater than 50. Notice how efficiently we use Reduce to complete both map and Filter methods at the same time?

const numbers = [10.20.30.40];
const doubledOver50 = numbers.reduce((finalList, num) = > {
  
  num = num * 2; 
  
  if (num > 50) {
    finalList.push(num);
  } 
  returnfinalList; } []); doubledOver50;/ / [60, 80]
Copy the code

1.2 Replacing Map and Filter with Reduce

If you read the above code carefully, you can understand that Reduce can replace Map and Filter.

1.3 Matching parentheses using Reduce

Another use of reduce is to be able to match parentheses in a given string. For a string containing parentheses, we need to know if the number of (and) is the same and before.

We can easily solve this problem using Reduce in the following code. We just have to declare a counter variable that starts at 0. When encountered (counter + 1, encountered) counter minus 1. If the number of parentheses matches, the final result is 0.

//Returns 0 if balanced.
const isParensBalanced = (str) = > {
  return str.split(' ').reduce((counter, char) = > {
    if(counter < 0) { //matched ")" before "("
      return counter;
    } else if(char === '(') {
      return ++counter;
    } else if(char === ') ') { 
      return --counter;
    }  else { //matched some other char
      returncounter; }},0); //<-- starting value of the counter}
isParensBalanced('() ()') // 0 <-- balanced
isParensBalanced('(asdfds)') //0 <-- balanced
isParensBalanced('(()') // 1 <-- not balanced
isParensBalanced(') (') // -1 <-- not balanced
Copy the code

1.4 Count the number of identical items in an array

A lot of times, you want to count the number of duplicate items in the array and represent them as an object. Then you can use the reduce method to process this array.

The following code will count the number of vehicles of each type and represent the total as an object.

var cars = ['BMW'.'Benz'.'Benz'.'Tesla'.'BMW'.'Toyota'];
var carsObj = cars.reduce(function (obj, name) { 
   obj[name] = obj[name] ? ++obj[name] : 1;
  return obj;
}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
Copy the code

There are so many other uses of reduce that I recommend reading MDN code examples.

2. Enforce parameters

ES6 provides a default argument value mechanism that allows you to set default values for arguments in case the function is called without passing them in.

In the example below, we write a required() function as the default for parameters A and b. This means that if either a or B does not pass a value when called, the required() function defaults and an error is thrown.

const required = (a)= > {throw new Error('Missing parameter')};

const add = (a = required(), b = required(a)) = > a + b;

add(1.2) / / 3
add(1) // Error: Missing parameter.
Copy the code

3. Object deconstruction

3.1 Deleting unnecessary Attributes

Sometimes you don’t want to keep certain object properties, perhaps because they contain sensitive information or are just too big. You might enumerate the entire object and then delete it, but in reality you simply assign the useless attributes to the variable and leave the useful parts you want to keep as the remaining parameters.

In the following code, we want to remove the _internal and tooBig arguments. We can assign them to internal and tooBig variables and store the remaining properties in cleanObject for later use.

let{_internal, tooBig, ... cleanObject} = {el1: '1'._internal:"secret".tooBig: {},el2: '2'.el3: '3'};

console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
Copy the code

3.2 Deconstructing nested objects in function arguments

In the following code, engine is an object nested within the object CAR. If we are interested in the Vin attribute of engine, we can easily get it using deconstructed assignment.

var car = {
  model: 'bmw 2018'.engine: {
    v6: true.turbo: true.vin: 12345}}const modelAndVIN = ({model, engine: {vin}}) = > {
  console.log(`model: ${model} vin: ${vin}`);
}
modelAndVIN(car); // => model: bmw 2018 vin: 12345
Copy the code

3.3 Merging Objects

ES6 brings extension operators (…) . It’s usually used to deconstruct arrays, but you can also use it for objects.

Next, we expand a new object using the extension operator, and the property values in the second object overwrite the property values of the first object. For example, the b and c of object2 overwrite the same attribute of Object1.

let object1 = { a:1.b:2.c:3 }
let object2 = { b:30.c:40.d:50}
letMerged = {... Object1,... object2}console.log(merged)
Copy the code

4. Sets

4.1 Using Set to implement array de-duplication

In ES6, because a Set stores only unique values, you can use a Set to remove duplicates.

let arr = [1.1.2.2.3.3];
let deduped = [...new Set(arr)] / / [1, 2, 3]
Copy the code

4.2 Using array methods on sets

The extension operator makes it easy to convert a Set to an array. So you can use all of Array’s native methods on sets.

Let’s say we want to filter the Set below to get items greater than 3.

let mySet = new Set([1.2.3.4.5]);
var filtered = [...mySet].filter((x) = > x > 3) / / [4, 5]
Copy the code

5. Array deconstruction

Sometimes you will put multiple values returned by a function in an array. We can use array deconstruction to get each of these values.

5.1 Value Exchange

let param1 = 1;
let param2 = 2;
[param1, param2] = [param2, param1];
console.log(param1) / / 2
console.log(param2) / / 1
Copy the code

5.2 Receive multiple results returned by the function

In the code below, we get a post from /post and the associated comments from/Comments. Since we are using async/await, the function puts the return value in an array. By using array deconstruction, we can assign the return value directly to the corresponding variable.

async function getFullPost(){
  return await Promise.all([
     fetch('/post'),
     fetch('/comments')]); }const [post, comments] = getFullPost();
Copy the code