Indexof/filter/foreach/map/reduce detailed in JS array

Source: Internet
Author: User
Tags pear

Today on the Internet to see a post, such as the Title:

Source: Front-End Development Blog (HTTP://CAIBAOJIAN.COM/5-ARRAY-METHODS.HTML)

In ES5, there are 9 array methods, namely:

Array.prototype.indexofarray.prototype.lastindexofarray.prototype.everyarray.prototype.somearray.prototype.foreacharray.p Rototype.mapArray.prototype.filterArray.prototype.reduceArray.prototype.reduceRight

1) indexOf

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

Via does not use indexof when the original is from: http://caibaojian.com/5-array-methods.html

var arr = [' Apple ', ' orange ', ' pear '],found = false;for (var i= 0, l = arr.length; i< l; i++) {if (arr[i] = = = ' Orange ') {foun D = true;}} Console.log ("found:", found);

After use

var arr = [' Apple ', ' orange ', ' pear '];console.log ("found:", arr.indexof ("orange")! =-1);
2) Filter

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

When no filter () is used

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);

The filter () is used:

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

var arr = [1,2,3,4,5,6,7,8];//Uses The usual ' for ' loop to iteratefor (var i= 0, l = arr.length; i< l; i++) {console.log (arr[i]);} Console.log ("========================");//uses ForEach to Iteratearr.foreach (function (item,index) {console.log ( item);});

foreach is used to replace a for loop

4) Map ()

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

Do not use map

var Oldarr = [{first_name: "Colin", last_name: "Toh"},{first_name: "Addy", last_name: "Osmani"},{first_name: "Yehuda", Last_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

var Oldarr = [{first_name: "Colin", last_name: "Toh"},{first_name: "Addy", last_name: "Osmani"},{first_name: "Yehuda", Last_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 a server to return Data.

5) Reduce ()

Reduce () can implement the function of an accumulator, lowering each value (from left to Right) of the array to a Value.

To tell the truth, it's a little difficult to understand this sentence, it's too abstract.

Scene: count the number of distinct words in an array

When you do not use reduce

var arr = ["apple", "orange", "apple", "orange", "pear", "orange"];function getwordcnt () {var obj = {};for (var i= 0, l = Arr.len Gth i< l; I++) {var item = arr[i];obj[item] = (obj[item] +1) | | 1;} Return obj;} Console.log (getwordcnt ());

After using reduce ()

code from Http://caibaojian.com/5-array-methods.htmlvar arr = ["apple", "orange", "apple", "orange", "pear", "orange"] function getwordcnt () {return arr.reduce (function (prev,next) {prev[next] = (prev[next] + 1) | | 1;return prev;},{});} Console.log (getwordcnt ());

Let me first explain my own understanding of reduce. Reduce (callback, Initialvalue) passes two Variables. The callback function (callback) and the initial value (initialvalue). Suppose the function has an incoming parameter, prev and next,index, and an array. Prev and next you have to Understand.

Generally speaking, prev starts with the first element in the array, and next is the second Element. But when you pass in the initial value (initialvalue), the first prev will be Initivalvalue,next will be the first element in the Array.

Like what:

/** the difference between the two, run it in the console to know */var arr = ["apple", "orange"];function nopassvalue () {return arr.reduce (function (prev, Next) {console.log ("prev:", prev); console.log ("next:", next); return prev + "+next;});} function Passvalue () {return arr.reduce (function (prev,next) {console.log ("prev:", prev), console.log ("next:", next); prev[next] = 1;return prev;},{});}
finally, thank the Great God for his guidance;
Source: Front-End Development Blog (HTTP://CAIBAOJIAN.COM/5-ARRAY-METHODS.HTML)

Indexof/filter/foreach/map/reduce detailed in JS array

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.