This is the 23rd day of my participation in Gwen Challenge. For details, see Gwen Challenge.
JavaScript offers a number of different ways to handle arrays, so I’ll take a few minutes to describe the array methods you can use in 10 projects.
1. Array.map()
Using the.map() method, you can create a revised array based on the original array. The.map() method takes a function that iterates through all the items in the array and modifies them accordingly.
The.map() method comes in handy when you need to update all the items in an array and store them in a new array.
For example, an array with a list of articles looks like this:
Const articles = [{article_id: "6976209276364652558", title: "How to pass the article_id in Vue ", views: 1258,}, {article_id: "6976113133358153736", title: "Angular State Management Framework: NgRx/Store", views: 2258,}, {article_id: "6975722363241365534", title: "Angular State Management Framework: NgRx/Store", views: 2258,}, {article_id: "6975722363241365534", title: "Angular PIPE ", views: 1568,},];Copy the code
Now get the array of all titles based on the list of articles above, as follows:
const arrayTitles = articles.map((item) => item.title);
console.log(arrayTitles);
Copy the code
The output is as follows:
[' How to pass parameters in Vue computed properties ', 'Angular Data State Management Framework: NgRx/Store', 'Introduction to Angular Pipes']Copy the code
Of course, you can use.map() for any array, and then add author information based on the above title array as follows:
Const arrayTitlesWithAuthor = arrayTitle.map ((title) => '${title}' console.log(arrayTitlesWithAuthor);Copy the code
The following output is displayed:
[' How to Pass Parameters in Vue computed Properties ', 'Angular Data State Management Framework: NgRx/Store ',' Introduction to Angular Pipes']Copy the code
The.map() method is a generic way to create a new array, modify its contents, and leave the original array unchanged. This is used when you need to modify the contents of an existing array and store the result as a new variable.
2. Array.filter()
It’s easy to tell from the name of the method what it does, yes, to filter array elements.
The filter() method fetches the elements of an array based on certain criteria and, like the.map() method, returns a new array, leaving the original array unchanged.
Obtain the articles with views < 2000 and articles > 2000 based on the articles array above:
const lessArticles = articles.filter((item) => item.views < 2000);
const muchArticles = articles.filter((item) => item.views > 2000);
console.log(lessArticles);
console.log("\r\n==========================================\r\n");
console.log(muchArticles);
Copy the code
The output is as follows:
[{article_id: '6976209276364652558', title: 'How to pass parameters in Vue ', views: 1258}, {article_id: '6976209276364652558', title:' How to pass parameters in Vue ', views: 1258}, {article_id: '6975722363241365534', title: 'Angular PIPE ', views: 1568 } ] ========================================== [ { article_id: '6976113133358153736', title: 'Angular Data State Management Framework: NgRx/Store', views: 2258}]Copy the code
When you need to remove elements from an array that do not meet certain criteria, use.filter().
3. Array.find()
The.find() method looks a lot like the.filter() method introduced earlier. As with the.filter() method, the element of the matched condition is returned, except that.find() returns only the first element that matches the supplied condition, not an array.
Change the.filter() method above to.find() as follows:
const lessArticle = articles.find((item) => item.views < 2000);
const muchArticle = articles.find((item) => item.views > 2000);
console.log(lessArticle);
console.log("\r\n==========================================\r\n");
console.log(muchArticle);
Copy the code
The following output is displayed:
{article_id: '6976209276364652558', title: 'How to pass parameters in calculated properties of Vue ', views: 1258 } ========================================== { article_id: '6976113133358153736', title: 'Angular Data State Management Framework: NgRx/Store', views: 2258}Copy the code
** When to use array.find ()? ** When we need to get the array by defining the first element of the condition.
4. Array.findIndex()
The.findIndex() method has the same name as the first part of.find() and performs the same function as.find(), except that it returns only the index value of the first element that matches the provided condition.
const lessArticle = articles.findIndex((item) => item.views < 2000); const muchArticle = articles.findIndex((item) => item.views > 2000); console.log(lessArticle); // 0 console.log(muchArticle); / / 1Copy the code
** When to use array.findIndex ()? ** When we need to get the index of the array in which the first element of the condition is defined.
5. Array.forEach()
The.foreach () method works much like a regular for loop, iterating through an array and executing a function on each element. The first argument to.foreach () is the callback function, which contains the current value and index of the loop array.
As follows:
Item. ForEach ((item, index) => {console.log(' ${item.title} '); });Copy the code
The following output is displayed:
Article index 0 is titled How to Pass parameters in Vue computed properties. Article index 1 is titled Angular Data State Management Framework: NgRx/Store. Article index 2 is titled Introduction to Angular Pipes.Copy the code
When you need to simply loop through each element of an array without having to build a new array.
6. for… of
for… Of is an es6 iterator that claims to be the simplest. It can terminate a loop with a break, continue, and return. Unlike.foreach (), no array index is provided. Much less code than the for statement, much more concise.
The following code iterates through the output array as follows:
for (const item of articles) {
console.log(item);
}
Copy the code
7. for… in
This method follows the one above for… Of looks similar in grammar, for… Of is a traversal of values, for… In is traversal of key/index. for… If you apply in to an array, key corresponds to the array index, and if you apply key to an object, key corresponds to the key.
To see the code execution effect, first apply to the array, as follows:
for (const key in articles) {
console.log(key);
}
Copy the code
The above code outputs the index values of the array: 0, 1, 2. This applies to the first object in the array as follows:
for (const key in articles[0]) {
console.log(key);
}
Copy the code
Article_id, title, views.
Use of for is discouraged in actual development. In. If you need to iterate over Object properties, you are advised to use Object.keys.
8. Array.every()
The.every() method checks if every element in the array passes the supplied condition, returning true if all elements in the array pass the condition, and false if not.
For example, check that all articles in the articles array have views over 1000, as follows:
const isMoreThan1000 = articles.every((item) => item.views > 1000);
console.log(isMoreThan1000); // true
Copy the code
Check the articles array for all articles with views over 2000 as follows:
const isMoreThan2000 = articles.every((item) => item.views > 2000);
console.log(isMoreThan2000); // false
Copy the code
** When is array.every () used? ** When you need to verify that each item in the array passes a defined condition.
9. Array.some()
The.some() method is similar to the.every() method, but validates the opposite, returning true if only one element in the array passes the condition, and false if all elements fail the condition.
The.some() and.every() methods explain how to implement logical and and or in the article 7 JavaScript Coding Tips you Should Know.
For example, check whether articles with views over 2000 exist in the articles array as follows:
const isMore2000 = articles.some((item) => item.views > 2000);
console.log(isMore2000); // true
Copy the code
Select * from articles where views > 3000 as follows:
const isMore3000 = articles.some((item) => item.views > 3000);
console.log(isMore3000); // false
Copy the code
10. Array.reduce()
A previous article, “javascript Arrays includes and Reduce,” was shared specifically for this approach.
The.reduce() method takes a callback function as its first argument and an optional initial value as its second argument. If no initial value is provided, the first array element is used as the value. The callback function provides an accumulator accumulator and currentValue parameters to perform a Reduce calculation.
Summing the views of a articles array
const sumViews = articles.reduce( (accumulator, current) => accumulator + current.views, 0 ); console.log(sumViews); / / 5084Copy the code
The.reduce() method can be used to flatten an array, but there are already many ways to do this, and this is one of them.
const flattened = [ [0, 1], [2, 3], [4, 5], ].reduce((accumulator, current) => accumulator.concat(current), []); console.log(flattened); // [0, 1, 2, 3, 4, 5]Copy the code
conclusion
JavaScript provides a number of different ways to handle arrays, and this article introduces 10 of the most common array handling methods used in daily project development.