Useful Functions

From rbachwiki
Revision as of 16:42, 2 December 2016 by Bacchas (talk | contribs)
Jump to navigation Jump to search

Map function

will duplicate an array to another
This will retrieve the ages of everyone 18 or over and add them to the array full

var ages[12, 13, 16, 21]
var full = ages.map(function(curr){
return cur >=18;
})

This will get the 'true' boolean value of ages>= 18 then we have to use the indexOf to find the element position

console.log(ages[full.indexOf(true)]);

ES6 Equivalent This returns the index

var index = ages.findIndex(cur => cur >= 18);

This returns the actual age

var ageover18 = ages.find(cur => 18);

Apply

 function addFourAges(a,b,c,d){
 return a+b+c+d;
 };
 var sum1 = addFourAges(18,19,20,21);

Each age is passed as a variable to the function, but if the ages were in an array, we can use the apply method to pass them into the function

var ages = [18,21,22,23];
var sum2 = addFourAges.apply(null, ages);
// the null refers to the this 

ES6 Equivalent Spread Operator

const sum3 = addFourAges(...ages);
// the ... means the ages array is expanded into individual components.

Join two Arrays


Splice

indexOf

Split

Used to split text given a delimiter into an array of substrings

var myText = 'hello-1'
var mysplit = myText.split('-')

Will Yield

['hello', 1]

Slice

Back To Top- Home - Category