Common methods for JavaScript arrays: indexOf, filter, ForEach, map, reduce usages __javascript

Source: Internet
Author: User
Tags pear
This article mainly introduces 5 array methods: IndexOf, filter, ForEach, map, reduce use examples, need friends can refer to the followingThe ECMASCRIPT5 standard, published on December 3, 2009, brings a number of new ways to improve the operations of existing array arrays. However, these novel array methods are not really popular because of the lack of browsers supporting ES5.

Array "Extras"

No one doubts the usefulness of these methods, but writing Polyfill (PS: Plug-ins compatible with older browsers) is not worthwhile for them. It turns "must-have" into "the best implementation". Some people actually refer to these array methods as an array "Extras". Hey.

But the times are changing. If you look at the popular open source JS project on GitHub, you will find that the trend is changing. Everyone wants to cut back on a lot of (third Third-party) dependencies, only in local code.

All right, let's get started.

my 5 arrays

In ES5, there are a total of 9 array methods http://kangax.github.io/compat-table/es5/

Note * Nine methods

Array.prototype.indexOf
Array.prototype.lastIndexOf
Array.prototype.every
Array.prototype.some
Array.prototype.forEach
Array.prototype.map
Array.prototype.filter
Array.prototype.reduce
Array.prototype.reduceRight

I'll pick 5 ways that I personally think are most useful and many developers will encounter.

1) indexOf

The IndexOf () method returns the position of the first element found in the array, or 1 if it does not exist.

When you don't use indexof?

1 2 3 4 5 6 7 8 9 10 var arr = [' Apple ', ' orange ', ' pear '], found = false;   for (Var i= 0, L = arr.length; i< l; i++) {if (arr[i] = = ' Orange ') {found = true;}} Console.log ("Found:", found);

After use?

1 2 3 var arr = [' Apple ', ' orange ', ' pear ']; Console.log ("Found:", Arr.indexof ("Orange")!=-1);

2) Filter

The filter () method creates an array of new matching filter criteria.

Without the filter ()?

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 var arr = [{' name ': ' Apple ', ' Count ': 2}, {' name ': ' Orange ', ' Count ': 5}, {' name ': ' Pear ', ' count ':     3}, {"name": "Orange", "Count": 16},];   var newArr = [];   for (Var i= 0, L = arr.length; i< l; i++) {if (Arr[i].name = = "Orange") {Newarr.push (arr[i]);} Console.log ("Filter results:", NEWARR);


Using the filter ():?

1 2 3 4 5 6 7 8 9 10 11 12-13 var arr = [{' name ': ' Apple ', ' Count ': 2}, {' name ': ' Orange ', ' Count ': 5}, {' name ': ' Pear ', ' count ':     3}, {"name": "Orange", "Count": 16},];     var newArr = arr.filter (function (item) {return item.name = = "Orange";}); Console.log ("Filter results:", NEWARR);

3) ForEach ()

foreach executes the corresponding method for each element?

1 2 3 4 5 6 7 8 9 10 11 12-13 var arr = [1,2,3,4,5,6,7,8];   Uses the usual ' for ' loop to iterate for (Var i= 0, L = arr.length; i< l; i++) {Console.log (arr[i));}   Console.log ("========================"); Uses ForEach to Iterate Arr.foreach (function (item,index) {Console.log (item);});

foreach is used to replace the For loop

4) Map ()

Map () After each element of the array is manipulated (mapped), a new array is returned,

Do not use map?

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 var Oldarr = [{first_name: "Colin", last_name: "Toh"},{first_name: "Addy", Last_Name: "Osmani"},{first_name: "Yehuda", L   Ast_name: "Katz"}];        function Getnewarr () {var newArr = [];      for (Var i= 0, L = oldarr.length; i< l; i++) {var item = Oldarr[i];      Item.full_name = [Item.first_name,item.last_name].join ("");    Newarr[i] = Item; return NEWARR; } console.log (Getnewarr ());

After using map?

1 2 3 4 5 6 7 8 9 10 11-12 var Oldarr = [{first_name: "Colin", last_name: "Toh"},{first_name: "Addy", Last_Name: "Osmani"},{first_name: "Yehuda", L   Ast_name: "Katz"}]; function Getnewarr () {return Oldarr.map (function (item,index) {item.full_name = [item.first_name,item.last_      Name].join ("");    return item;     }); } console.log (Getnewarr ());


Map () is a very useful function when processing the server to return data.

5) reduce ()

Reduce () can implement an accumulator function that lowers each value of the array (left to right) to a value.

To be honest, it is a little difficult to understand this sentence, it is too abstract.

Scenario: Counting how many words in an array are not repeated

When you are not using reduce?

1 2 3 4 5 6 7 8 9 10 11 12 13-14 Var
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.