Skip to content

Instantly share code, notes, and snippets.

@rizalp
Last active December 16, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rizalp/5467471 to your computer and use it in GitHub Desktop.
Save rizalp/5467471 to your computer and use it in GitHub Desktop.
JavaScript: Array & basic Functional Paradigm
var foo = [11, "hello", true],
length = foo.length();
off = foo.slice(); //off is now copy of foo
fff = foo.slice(1); //fff is now ["hello", true]
var eleven = foo[0];
foo[foo.length] = "whatever, new value and index can be created dynamically";
foo.push("a new value pushed to the array");
//literal syntax. Easy
var names = ["Jeremy", "Jeffrey"],
names2 = ["Jennifer", "Jackie"];
// Jeremy,Jeffrey,Jennifer,Jackie
var people = names.concat(names2); //names and names2 concatted
// Jeremy, Jeffrey, Jennifer, Jackie
var joined = people.join(", "); //join the array into single string
var reversed = people.reverse(); //Jackie,Jennifer,Jeffrey,Jeremy
var sorted = people.sort(); //sorting the array
//STACK - like functionality in Array
var mack = [];
mack.push("Mack");
mack.push("the");
mack.push("Knife");
alert(mack.join(" "));
alert(mack.pop());
alert(mack);
var fruit = ["apple", "oranges", "bananas", "grapes"];
fruit.indexOf("apple"); //0
//it will be usefull on the functional programing later
//this type of function is unique.
//value, index, and array corresponds to the function caller
/*
value: apple, index: 0, array: apple,oranges,bananas,grapes
value: oranges, index: 1, array: apple,oranges,bananas,grapes
value: bananas, index: 2, array: apple,oranges,bananas,grapes
value: grapes, index: 3, array: apple,oranges,bananas,grapes
*/
function isString(value, index, array) {
return typeof value === "string";
}
//return true if minimum one is true
fruit.some(isString);
//return true if every element is true
fruit.every(isString); //notice that the call doesn't include brackets
function startWithAB(value, index, array) {
return value[0] === "a" || value[0] === "b";
}
var result = fruit.filter(startWithAB); // returns only the element that MATCH the condition
function doSomething(value, index, array) {
alert(value);
}
fruit.forEach(doSomething) //run function for each of the element
function mapSomething(value, index, array) {
return "i like" + value
}
var result = fruit.map(mapSomething) //map new element into the result​​​​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment