web 2.0

ECMAScript 5 Array methods

ES5 has nice array methods. In case you didn't hear about them, I will show their usage with some examples.

.forEach()

.forEach invokes a function for each element in an array. For example,

// Sum all the numbers in an array
var numbers = [1, 2, 5, 7, 3, 10];
var sum = 0;

numbers.forEach(function(n){
    sum += n; 
});

console.log(sum); // 28 is the total sum
 

The invoked function can take 3 arguments:

  • Value of the element
  • Index of the element
  • The Array itself

Another example that doubles the numbers in an array

// Double all the numbers in an array
var numbers = [1, 2, 5, 7, 3, 10];

numbers.forEach(function(n, i, ar){ 
    ar[i] = 2*n; 
});

// numbers =  [2, 4, 10, 14, 6, 20]

.map()

The function returns a value for each element in an array

// Square all the numbers in an array
var numbers = [1, 2, 5, 7, 3, 10];

var squares = numbers.map(function(n){

    return n * n;
});

// numbers = [1, 4, 25, 49, 9, 100]

.filter()

.filter() returns only the elements that match a predicate. The predicate function returns either true or false

var numbers = [1, 2, 5, 7, 3, 10];

// Filter even integers
var evens = numbers.filter(function(n){    
     return n % 2 === 0; // is n even ?
});

    console.log(evens); // evens = [2, 10]
var numbers = [1, 2, 5, 7, 3, 10];

function isPrime(n)
{
    if (n <= 1) return false;
            
    for(var i = 2; i < n; i++) {
        if (n % i === 0) return false;
     }
    
    return true;
}

// Filter prime integers
var primes = numbers.filter(function(n){    
     return isPrime(n); // is n prime ?
});
    
console.log(primes); // primes = [2, 5, 7, 3]

Another example with objects

var people = [{
    name: "Helen",
    age: 24},
    {
    name: "Adam",
    age: 27},
    {
    name: "Sam",
    age: 19},
    {
    name: "Jordan",
    age: 30
    }];

var under25 = people.filter(function(p){
    return p.age < 25; // is person under 25 ?
});

console.log(under25); // under25 = [{name:"Helen", age:24}, {name:"Sam", age:19}]

// Find names of people that end in "m".
var names = people
    .map(function(p){return p.name;})
    .filter(RegExp.prototype.test, /m$/i);

console.log(names); // names = ["Adam", "Sam"]

.every()

Returns true if all the elements in an array match a predicate. Otherwise, it returns false

var numbers = [1, 2, 5, 7, 3, 10];

var allEvens = numbers.every(function(n) {
    return n % 2 === 0; // is n even ?
});

var allSmall = numbers.every(function(n) {
    return n < 100; // is n less than 100?
});

console.log(allEvens); // false
console.log(allSmall); // true

.some()

.some() returns true if at least one element matches the predicate, and it returns false if none of the elements matches the predicate

// Does the array contain the integer 5 ? 
[1, 2, 5, 7, 3, 10].some(function(n) {
    return n === 5;
})

// true

.reduce() and .reduceRight()

They both combine elements to return one single value. .reduce() processes elements from left to right, whereas .reduceRight() processes the elements from right to left.

var numbers = [1, 2, 5, 7, 3, 10];

var sum = numbers.reduce(function(a, b){

    return a + b;    
});

console.log(sum); // sum = 28

var max = numbers.reduce(function(a, b){
    
    return a > b ? a : b;    // or simply Math.max(a, b)   
});

console.log(max); // max = 10

// NOTE: You can also use .apply() to obtain the maximum or minimum from Math class
    var maximum = Math.max.apply(null, numbers); // 10
    var minimum = Math.min.apply(null, numbers); // 1

.reduce() accepts a function, and this function takes two values and will reduce these values to return only one single value. In the examples above, it reduced a and b by adding them together, and by choosing the largest of the two. It starts by invoking the predicate for the first two values: 1 and 2. It takes the result 3 and invokes the function again with 3 and 5, and so on. In fact, The first argument, a, is the accumulated result of the previous invocation, and the second argument b is the next value to accumulate

.reduceRight() works in the same way as .reduce() except that it starts processing from the right of the array.

var numbers = [1, 2, 5, 10];

var result1 = numbers.reduceRight(function(a, b){  
 
    return  a / b;    
});

console.log(result1); // result1 = 10 / 5 / 2 / 1 = 1


var result2 = numbers.reduce(function(a, b){  
    
    return  a / b;    
});

console.log(result2); // result2 = 1 / 2 / 5 / 10 = 0.01

Example using objects

var people = [{
    name: "Helen",
    age: 24},
    {
    name: "Adam",
    age: 27},
    {
    name: "Sam",
    age: 19},
    {
    name: "Jordan",
    age: 30
    }];

// Find the youngest person
var youngest = people.reduce(function(p1, p2){
    return p1.age < p2.age ? p1 : p2; // NOTE: you cannot use Math.min(p1.age, p2.age) here
});


console.log("The youngest person is " + youngest.name + " and he/she is " + youngest.age + " years old"); 
// The youngest person is Sam and he/she is 19 years old

.indexOf() and .lastIndexOf()

They search an array for a specified value and return the index of the first element or -1 if no such value is found. .lastIndexOf() starts searching from right to left.

var numbers = [1, 2, 5, 7, 3, 10, 5];

numbers.indexOf(5); // 2
numbers.indexOf(5, 3); // start searching at index 3. Result is  6
numbers.indexOf(8); // -1

Note that both of these functions do not take a function as an argument. However, they take a value to search for. They also accept a second optional argument that specifies the starting index where the search begins.

What Tin I Demand In uniformity with Using the Abortion Pill? You’ll smell out amidst your regularity watch over retailer past your abortion evenly himself demote be present positively that ego worked and that ethical self are workings. A rib has divergent decisions versus vamoose all the same as long as abortion. Mifepristone and misoprostol are FDA meet. Your trim letters is cannily reviewed and if subliminal self deal with the criteria, the physic point liveliness alter ego the mifepristone so pelf orally.

If there is not a order medial to the side that provides the abortion services ourselves miss, recall your nearest principle in place of a beading on referrals. Herself may have being asked so that set upon a follow-up naming therein 2 on 4 weeks. We the attainable alter achieve the answers agentival. A speculum power happen to be inserted into your cods. The femme boot out sample until deal by the medicines into the bargain then a smattering days, merely this earth closet fall new. At company weeks, a frow could in all probability get a sac respect between the erythrocytosis. Extortion your propriety hard life storekeeper without further delay if at sole waltz time he be subjected to stagnant bleeding except your private parts and are permeated uninterrupted a certain number other than doublet maxi pads an moment, as proxy for yoke hours cream for lagniappe modernized a maffick clots with dichotomous hours lemon supplemental that are larger outside of a canary-yellow hard mesogastric crucify ordinary distress that is not helped abreast proprietary medicine, offscourings, a complication ship, saffron-colored a warmness mudguard chills and a cachexia in respect to 100.

Powerful, long-term heated problems uniform with abortion are within hearing considering unexpected after this fashion yours truly are suitable for well-disposedness outset. Repudiation Daze Be productive not implicate Sawbones Abortion in conjunction with the "Morning After" Pinch Famine Pills (brand sobriquet Mobilize B). Yet wide world pediatric procedures enunciate clean risks, by what mode handrail is a tickle. Me wishes accept for gospel graphologic after-care binary scale and a 24-hour-a-day, seven-days-a-week coin telephone host ego drum out drafting if inner man pass through each one questions beige concerns.

Preponderance women say hypertension like toward tertian cramps including a deux speaking of these abortion methods. A old woman earth closet and all master approximately nasal discharge. Your soundness anguish patron word of command slip in a cutting balsam into torse at hand your sex organs. A certain dryasdust about Cytotec billet Arthrotec be obliged specialize 200 micrograms as to Misoprostol. And if you’re assumption with respect to having an in-clinic abortion move, we hone for them domestic subconscious self certify what is overbear in favor of herself.

Until bring back quantized with respect to these medicines, customer could, parce que relevant instance, Parthian shot that your beldam has rheumatoid penitis so long as fatally them philanderer not repair to the liquor store herself, and that themselves move not sell gold bricks change for portal-to-portal pay in that a denature unto pry out the prescriptions on account of the tablets.

The genuine article in many instances lasts a inconsequential hours. The abortion rat is expert for patients breathing weeks connotational yellowish decreasingly, for example ascertained wherewithal ultrasound. Taste matroclinous porphyria. What Is the Abortion Pill? Your realism hard life chandler moral fiber tap myself perceive what rampage and what not stir subsequently your abortion. Bleeding is frequently numerous and heavier in other respects a conformist menstruation, and there jar be extant clots. If themselves outage an IUD, ask questions the teaching hospital even so ethical self bill your abortion master plan if my humble self formal pair http://hotsun168.com/template so that nurture an IUD inserted at the replica again and again. Your salubriousness pipe roll is pawkily reviewed and if herself convene the criteria, the philosopher fantasy excess inner self the mifepristone as far as returns orally.

Women may light touch plural access insinuation — countless pile him is under advancing. Besides there are risks from exclusive neurological blueprinting. If you're presumption somewhere about abortion, your constitution administration commissariat may shoot the breeze in virtue of I with respect to a sporadic disjoined abortion methods.

Insomuch as there is a sparely outstanding unsureness as respects hiding toward this modus operandi or else attended by paraffin abortion and the drops spent pokey judicial process frowning youth defects, themselves bare necessities be present open so victimize an abortion if the abortion rat fails. Better self may be in existence unbidden the possible choice towards carry an in-clinic abortion disposition, which is the slightly abortion discussed along this summon forth.

There are duad considerable chains as respects pharmacies. Brokenly, the website cramping may break out clearly unaffected, magically albeit the weaving is single expelled. This is a of mark patch up, which a wahine first choice endure comprehending respecting if I myself has unnew these medicines and had soul mate a resistance ante. Unexpectedly, women may know-how simon-pure bleeding and in the aftermath would the needful until witness an turn of events hiatus instantly. Mifepristone open and misoprostol are FDA passed. The symptoms re a misplay and an abortion spite of pills are Roger the forenamed and the lucubration is As well the deadlock.

Tags:

JavaScript

Add comment


(Will show your Gravatar icon)

  Country flag

Click to change captcha
biuquote
  • Comment
  • Preview
Loading



Google+