In the new year, we will learn these useful methods

JavaScript It gives us a lot of different ways to deal with arrays . We will introduce to you in a few minutes 7 This is a basic and common data method , To improve your JS Develop skills .

1. Array.map()

When you use on arrays map() Method time , It will create a new array in the original array .

This map() Method takes a parameter , This argument is a function , This function can loop or traverse every element in the array , You can also modify every element in it , Then the combination returns a new array .

When you want to modify or update its elements in an array , And then store it in a new array , This .map() The method will come in handy .

Suppose we have an array of car brands :

const cars = ["Porsche", "Audi", "BMW", "Volkswagen"];

Of course , We think all the cars are cool , We want to add some words to express this . We can use .map() Method :

const coolCars = cars.map((car) => `${car} is a pretty cool car brand!`);
// result :
[
"Porsche is a pretty cool car brand!",
"Audi is a pretty cool car brand!",
"BMW is a pretty cool car brand!",
"Volkswagen is a pretty cool car brand!",
];

here , This map() Method is used to create a new modified array

fantastic ! that map() Method creates a new array , And add text to each element .

Sometimes arrays contain objects (object), How should we operate ?

Let's look at the following example , Add a price attribute to this car , The situation of becoming an object :

const carsWithPrice = [
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
]; const carsWithPriceAndTax = cars.map((carObject) => {
return {
// Return the original car object
...carObject,
// but also add a new value containing the price with tax
priceWithTax: carObject.price * 1.2,
};
}); // result :
[
{ brand: "Porsche", price: 100000, priceWithTax: 120000 },
{ brand: "Audi", price: 80000, priceWithTax: 96000 },
];

Use map() Method to create a new array containing prices with tax

All in all ,map() Method is a very common method , Used to create a new array 、 Modify its contents and leave the original array unchanged .

When to use Array.map()?

When you want to modify the contents of an existing array and store the results as a new array .

2. Array.filter()

You can almost guess what this method is .

This .filter() Method allows you to get elements in an array based on specific conditions .

It's like map() The method is the same , It will return a new array and leave the original array unchanged .

for example , Examples of using cars , We can filter the array based on the car price being higher than a certain value .

ad locum , We have all the cars available :

const cars = [
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
{ brand: "Toyota", price: 30000 },
];

Now? , Suppose all values 40,000 Or more cars are expensive .

We can use filter() All the ways “ cheap ” and “ expensive ” The car .

const expensiveCars = cars.filter((car) => car.price >= 40000);
const cheapCars = cars.filter((car) => car.price < 40000); // result - Your car
[
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
]; // result - Cheap car
[{ brand: "Toyota", price: 30000 }];

Use the filter method to filter... From an array " cheap "、" expensive " The car

Check each element of the array , See if it meets the standard , If the test passes , It will be returned in a new array .

When to use Array.filter()?

When you want to remove from an array that does not meet certain conditions / Element of condition .

3. Array.reduce()

Now this may be a little hard to understand .

In short , Call in array .reduce() Method , It iterates through each element of the array by executing a function or method , Finally, a value is returned .

that reduce() Method takes the callback function as its first parameter , And take the optional initial value as its second parameter . If no initial value is provided , The first value of the array is used . This callback function will provide accumulator and currentValue Parameters are used for execution reduce Calculation .

I know it can be a little complicated , But never mind. .

Here's a simple example to show reduce() Method :

Suppose we want to get the total value of all the numbers in the array .

const numbers = [13, 65, 29, 81, 47];

then , We can use reduce () Method adds all these values together .

const total = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
); // result - total :
235;

Use reduce Method to add all the values of the array

Another way to use reduce() Function to flatten the array , There are already many ways to do this , This is one of them .

const flattened = [
[0, 1],
[2, 3],
[4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])[
// Result - Flattened:
(0, 1, 2, 3, 4, 5)
];

Use reduce Method flattens the array

When to use Array.reduce()?

When you want to convert an array to a single value by manipulating the value of the array .

4. Array.forEach()

Now it's a classic .

that forEach() The method works much like a routine for loop .

It loops over the array and executes a function for each item . .forEach() The first argument to is a function , Parameters of this function , Contains the current value and index of the elements of the array .

Let's look at an example of a car :

const cars = [
{ brand: "Porsche", price: 100000 },
{ brand: "Audi", price: 80000 },
{ brand: "Toyota", price: 30000 },
];

We can traverse the elements in the array , use console.log You can input the brand name and price of the car .

cars.forEach((car) => {
console.log(`The ${car.brand} will cost you ${car.price} before taxes`);
}); // result :
("The Porsche will cost you 100000 before taxes");
("The Audi will cost you 80000 before taxes");
("The Toyota will cost you 30000 before taxes");

Use forEach How to cycle all the cars , Then text out its brand name and price .

When to use Array.forEach()?

When you want to simply loop each element of any array without constructing a new array .

5. Array.find()

This .find() The method is very similar to what we said before .filter() Method .

It's like .filter() Method , You will be able to pass conditions that array values must match .

The difference between the two is .find() Only the first element that matches the criteria you provide will be returned .

Take the car for example , Let's use .find() Method to find the first most expensive car in the array :

const cars = [
{brand: "Porsche", price: 100000},
{brand: "Audi", price: 80000},
{brand: "Toyota", price: 30000}
]; const expensiveCar = cars.find(car => car.price >= 40000);
// result - Your car :
{brand: "Porsche", price: 100000}

Use .find() Method to find the first car in the array “ expensive ” automobile

When to use Array.find()?

When you want to find the first value in the array that meets the condition

6. Array.every()

Maybe you can already guess what this method does .

This .every() Method will check that all elements in the array pass the conditions provided .

If all elements in the array pass the condition , The method will return true. otherwise , It will return false.

for example , We can use .every() How to check whether all the cars can be in 5 Made in the next year .

const cars = [
{ brand: "Porsche", price: 100000, builtIn: 2018 },
{ brand: "Audi", price: 80000, builtIn: 2019 },
{ brand: "Toyota", price: 30000, builtIn: 2019 },
];
const carsYoungerThanFiveYears = cars.every((car) => car.builtIn >= 2016);
// Result - Younger than 5 Years:
true;

Use .every() How to determine if all the cars are in 5 Manufactured during the year

When to use Array.every()?

When you want to make sure that all elements in an array meet certain conditions .

7. Array.some()

.some() It's a little like that .every() Method , But not all the elements meet the conditions before passing the test , But as long as one of the elements satisfies the condition , It will pass the test .

as long as .some Method to find the successful array element , It stops traversing the search , It will return true, then , If you don't get to the last element , It will return false.

Let's use our car array again , But this time we're going to check whether some cars are more than 5 year .

const cars = [
{ brand: "Porsche", price: 100000, builtIn: 2018 },
{ brand: "Audi", price: 80000, builtIn: 2019 },
{ brand: "Toyota", price: 30000, builtIn: 2019 },
]; const carsOlderThanFiveYears = cars.some((car) => car.builtIn < 2016); // result - Less than 5 Year of :
false;

When to use Array.some()?

When you want to see if there are any elements in the array that meet the conditions

summary

These methods are very simple to learn and understand , Just write more examples , We can often apply them to various projects .

stay 2021 What you need to master in this year 7 for JavaScript More related articles on array methods of

  1. JDBC Basic operation

    1. brief introduction JDBC(Java DataBase Connectivity) There are some interfaces and classes API JDBC yes J2SE Part of , also java.sql: javax.sql Package composition .   Applications ...

  2. ACM Study

    turn :ACM A large number of problem banks   ACM A large number of problem banks Now there are many question banks on the Internet , Most of them can be evaluated online , So it's called Online Judge. except USACO Is for IOI Get ready to go outside , Almost all of the rest are from universities ACM Competition question bank .   US ...

  3. ( Reprint )ACM Training program , Let's go through the foundation first, and then fight according to it !!!!

    ACM A large number of problem banks ACM A large number of problem banks   Now there are many question banks on the Internet , Most of them can be evaluated online , So it's called Online Judge. except USACO Is for IOI Get ready to go outside , Almost all of the rest are from universities ACM Competition question bank . USACO ht ...

  4. jqu

    1 /*2 * explain :3 * The Chinese annotation of this source code is Auscarlin With all my heart . To promote jQuery And to the general public jQuery Fans offer an advanced 4 * Way , To give you a deeper understanding of jQuery, learn ...

  5. the other one ACM It's a way to suggest

    ACM Contact advice An expert's advice to me : In general, we should do 50 There is no need to debug the program within the line .100 Debugging is successful within two minutes .acm It's mainly about algorithms , The main time is spent thinking about algorithms , It's not about writing programs and debug On . Here's a plan ...

  6. product Spring: I never thought. , Thirty steps to finish a bean Instance creation

    When the start of the container is almost finished , I'll give you all the examples bean instantiate , It can also be called pre instantiation . One of the benefits of doing so is , Can find problems early , Throw an exception early , Get rid of it early . This article will take a look at the whole instantiation process . In fact, it's more complicated . ...

  7. JS The original surface is from entry to abandonment Length is longer than the , Recommended collection

    Preface It's time for a wave JS The foundation , Well done , Take ten silver quickly offer; This article is not from the traditional way of question and answer , But from the perspective of knowledge , In order to form a knowledge network ; Include function , Array , object , data structure , Algorithm , Design patterns and http. function ...

  8. InfoQ A wave of articles :AdaSearch/JAX/TF_Serving/leon.bottou.org/Neural_ODE/NeurIPS_2018 Best paper

    and Nested Partition There is something in common ? Berkeley put forward AdaSearch: A step-by-step elimination method for adaptive search Among the many tasks in the field of machine learning , We usually want to be able to find the answer to the question based on the fixed data set given in advance ...

  9. Image Processing and Computer Vision_Review:Local Invariant Feature Detectors: A Survey——2007.11

    translate Local invariant feature detector : A survey Abstract - In this survey , We outline the invariant point of interest detector , How they develop over time , How they work , And their respective advantages and disadvantages . We first define the properties of the ideal local feature detector . Next ...

  10. &lt;JavaScript&gt; How to read 《JavaScript Advanced programming 》( One )

    Digression Recently in to see <JavaScript Advanced programming > This book , Face 700 Many pages of thick books , There's a little bit of pressure in my heart , So I decided to sort it out .. Explore how to read this book . The content of this book seems to be limited to ES5... So only ...

Random recommendation

  1. FMDB Exclusive lock

    ------------------------------------- Basic operation ------------------------------------- #import "ViewCon ...

  2. One a day Linux command

    One a day Linux command (1):ls command One a day Linux command (2):cd command One a day Linux command (3):pwd command One a day Linux command (4):mkdir One a day Linux command (5) ...

  3. Java Decompilation tool -Jad, Jode, Java Decompiler Etc IDE plug-in unit

    from :http://blog.csdn.net/superbeck/article/details/5189231 For long-term use Java The programmer , Most of them will use decompiler software more or less . After all , impossible ...

  4. SSDB

    A high-performance system supporting rich data structure NoSQL database , Used in substitution Redis. characteristic replace Redis database , Redis Of 100 Times the capacity LevelDB Network support , Use C/C++ Development Re ...

  5. Chinese character coding :GB2312, GBK, GB18030, Big5

    The previous post :ANSI What's the code ? There is a little story in the book : The computer is made by Americans , They think a byte ( Can be said 256 Encoding ) It means all the letters in the English world . Numbers and common special symbols are more than enough ( Actually ASCII ...

  6. linux Simple text processing

    1. Determine the value of the first column based on the data of the second column awk '{if(a!=$0)i++;print i,$0;a=$0}' arr >arr.out 2. Make up the length seq arr.out|awk '{p ...

  7. C++ in , Reference as function parameter

    Reference as function parameter C++ The reason for adding reference types , It's mainly a function parameter , The function of transferring data by extension function . ———————————————————— c++, Function arguments :(1) Take the variable name as an argument and a formal parameter . And then it's passed to the formal parameter ...

  8. Soft work +C(6): Recent development zone / The scaffold

    // Last one : Tools and structure // Next : Wild programmer It's mentioned in educational psychology " Recent development zone " The concept , This concept is the former Soviet development psychologist Vygotsky (Vygotsky) Proposed , The English noun is Zone ...

  9. history.go(-1) Parsing in different browsers

    There's a problem today : <a href="#" onclick="history.go(-1)"> back off </a> Click on " back off " ...

  10. unittest Initialization and restoration of test environment in unit test framework (fixture)( 5、 ... and )

    1. Method 1 : Initialize and restore each test case import unittest from UnittestDemo.mathfunc import * class TestMathFunc(unitte ...