Seven array methods for JavaScript you need to master in 2021

School of knowledge programming 2021-02-23 12:31:17
array methods javascript master


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 .

版权声明
本文为[School of knowledge programming]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223123029159g.html

  1. JS mechanism 3: stack, heap, garbage collection
  2. [grid compression evaluation] meshquan, meshopt, Draco
  3. Deep understanding of Vue modifier sync [Vue sync modifier example]
  4. WebView for front end engineers
  5. React form source code reading notes
  6. Deep thinking about modern package manager -- why do I recommend pnpm instead of NPM / yarn?
  7. On the sequence of event capture and event bubbling
  8. Help you build a systematic understanding of the front end scaffolding
  9. commander.js Principle analysis
  10. Common usage of nginx
  11. H5 jump to wechat app
  12. Front end algorithm interview must brush questions series [14]
  13. Thinking of cross end practice
  14. Vue server rendering principle analysis and introduction
  15. [KT] vscode plug in development example series (2)
  16. Design ideas of react and Vue framework
  17. JavaScript String.prototype.replaceAll 兼容性导致的问题
  18. JavaScript String.prototype.replaceAll Problems caused by compatibility
  19. 爱奇艺体育:体验Serverless极致扩缩容,资源利用率提升40%
  20. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  21. 对前端异常window error捕获的全面总结
  22. A comprehensive summary of front end exception window error capture
  23. 成功解决Problem while trying to mount target]\“. HTTP response code is 400
  24. Problem while trying to mount target] \ ". HTTP response code is 400
  25. 放弃okhttp、httpClient,选择了这个牛逼的神仙工具!贼爽
  26. 前端面试每日 3+1 —— 第679天
  27. How to add elements at the beginning of an array in JS?
  28. Give up okhttp and httpclient and choose this awesome immortal tool! Thief Shuang
  29. Front end interview daily 3 + 1 - day 679
  30. 【2021 第一期】日常开发 26 个常见的 JavaScript 代码优化方案
  31. Daily development of 26 common JavaScript code optimization schemes
  32. 前端的字符串时间如何自动转换为后端Java的Date属性,介绍springMVC中如何解决时间转换问题
  33. How to automatically convert the front-end string time to the back-end Java date attribute, and how to solve the time conversion problem in spring MVC are introduced
  34. 前端面试常考题:JS垃圾回收机制
  35. ReactDOM.render串联渲染链路(一)
  36. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  37. 粗涉Webpack
  38. Frequently asked questions in front end interview: JS garbage collection mechanism
  39. ReactDOM.render Serial rendering link (1)
  40. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  41. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  42. About webpack
  43. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  44. 详解vue静态资源打包中的坑与解决方案
  45. 一篇搞懂TCP、HTTP、Socket、Socket连接池
  46. 字节跳动2021前端技术岗发布+最新内部面试题
  47. Detailed explanation of Vue static resource packaging and Solutions
  48. Understanding TCP, HTTP, socket, socket connection pool
  49. 2008-2021 front end technical post release + latest internal interview questions
  50. 4. Vue基本指令
  51. 4. Vue basic instruction
  52. Java 发起 http 请求
  53. Java initiates HTTP request
  54. 网站由http升级为https图文教程
  55. Upgrade the website from HTTP to HTTPS
  56. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  57. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!
  58. 混合开发入门 Vue结合Android/iOS开发仿京东项目App
  59. Hybrid development entry Vue combined with Android / IOS to develop app imitating Jingdong project
  60. 无缝对接 Tableau,这家月活跃用户 5000+ 的大型银行如何实现自助式分析?