Javascript--map, reduce, filter, Sort__java

Source: Internet
Author: User
Tags pow

Map -JavaScript is case-sensitive, map is the data type, and map is the method defined in the array.

The map () method is a higher-order function than the iterable foreach () method. Map () performs its parameter function on each of these elements.

eg

var array1 = [1,2,3];
function Pow (x) {return
	x*x
}
Array1.map (POW);   -->array1  [1,4,9]

reduce --same as map,reduce is defined in the array

Reduce () is also a higher-order function. Reduce () The elements within the array are performed with the index from small to large 22 for parameter function operations [the first and second operations get new, this new and third operation, get the new, this new again and the fourth operation ... ]。

[A,b,c].reduce (f) = f (f (a,b), c)

eg

var array1 = [1,2,3];
function Add (x,y) {return
	x + y;
}
Array1.reduce (add);  -->6

Filter--> filters, with map (), filter to the array of each element of the function parameters of the operation, but the function parameter return value is true, the elements inside the array is preserved, otherwise discarded, so, A function parameter is actually a judge of whether an element within an array meets a condition

eg

var array1 = [1,2,3,4,5];
Array1.filter (function (Element) {return
	element% 2!== 0;
});

Discard the even numbers in the original array.

Sort--> This method is interesting, sort, and also a higher order function

This function defaults to first convert the elements inside the array to a string and then sort

So

var array1 = [2,3,10];
Array1.sort ();    -->[3,2,10]

When the function argument for sort () is empty, the default sort is to first convert the array elements to "2", "3", "10", so why the result of this sort is clear.

Therefore, the General sort () is used as follows: (the function parameter is not NULL)

var array1 = [2,3,10];
Array1.sort (function (x,y) {
	if (x > Y) {return
		1;
	} else {
		return-1;
	}
});    -->[10,3,2]






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.