Skip to content

Instantly share code, notes, and snippets.

@hugolpz
Last active March 15, 2021 18:39
Show Gist options
  • Save hugolpz/f9ca3588d08d2409e9e5322f9dd05d25 to your computer and use it in GitHub Desktop.
Save hugolpz/f9ca3588d08d2409e9e5322f9dd05d25 to your computer and use it in GitHub Desktop.
Frugal tutorial 01 : Javascript Array methods.
// DATA : few common array samples to manipulate.
var letters = ['a', 'b', 'c'],
numbers = [2, 3, 4, 5, 6, 7, 8],
members = [
{ 'name': 'A', 'group':'Bird', 'rank': 1, 'age': 24},
{ 'name': 'B', 'group':'Wolf', 'rank': 3, 'age': 12},
{ 'name': 'C', 'group':'Fox', 'rank': 2, 'age': 9},
{ 'name': 'D', 'group':'Bird', 'rank': 4, 'age': 27}
];
var bin= [];
// FOREACH, MAP, REDUCE
// [].forEach() : process over something
['a', 'b', 'c'].forEach(function(item, index, initialArr) {
// do some processing here.
if(index===0) console.log('[].forEach(): ', initialArr, item, index, this, this[index]);
}, [4, 5, 6]);
['a', 'b', 'c'].forEach(item => bin.push(item.toUpperCase() ));
console.log('[].forEach():', bin) // ['A', 'B', 'C']
// [].map() : creates new array populated with the results of each element, itself processed by custom function
var groupsAll = members.map(function(member) { return member.group; });
var groupsAll = members.map(member => member.group);
console.log('[].map(): ', groupsAll) // ["Bird", "Wolf", "Fox", "Bird"]
// [].reduce() : iterate through array and process from initial value by custom operation (sum, multi, etc), resulting in single output value.
var experience= members.reduce(function(intermediateResult,item) { return intermediateResult + item.age; }, 0)
var experience= members.reduce( (intermediateResult,item) => intermediateResult+item.age, 0 )
console.log("[].reduce(): "+ experience) // 72
// FILTER & FIND
// [].filter() : creates new array with all elements that pass the condition.
var passFilter = numbers.filter(function(number) { return number >= 6});
var passFilter = numbers.filter(number => number >= 6);
console.log('[].filter(): ',passFilter); // [6,7,8]
// [].find : returns value of first element matching condition.
var found = members.find(function(member) { return member.age > 5; });
var found = members.find(member => (member.age > 5));
console.log('[].find(): ',found) //{ age: 24, group: "Bird", name: "A", rank: 1 }
// SOME & EVERY
// [].some() : check if one or more elements respect condition, returns true or false.
var majorPresent = members.some(function(member,i,arr){ return member.age >= 18 });
var major = members.some(member => member.age > 18);
console.log('[].some(): ', majorPresent) // true
// [].every() : check if every elements respect condition, returns true or false.
var majorOnly = members.every(function(member,i,arr){ return member.age >= 18 });
var major = members.every(x => x.age > 18);
console.log('[].every(): ', majorOnly) // false
// SET (Uniques)
// [] Set : process to create array of values without any duplication
var namesUniq = [...new Set(members.map(member => member.group))];
console.log("Uniques: ", namesUniq )
// SLICE & SPLICE
// [].slice([start[, end]]) : creates new array with elements from index 'start' to index 'end'
var kept = numbers.slice(2,5);
console.log(kept)// [4,5,6]; `numbers` unchanged.
// [].splice(x,n) : remove from item==x, for n items.
var numbers2= numbers;
var deleted = numbers2.splice(2, 3);
// numbers2 now [1, 2, 6, 7, 8]
// deleted is [3, 4, 5]
// Compare 2 arrays
let intersection= arrA.filter(x => arrB.includes(x)); // Intersection
let difference = arrA.filter(x =>!arrB.includes(x)); // In A only
let union = [...new Set([...arrA, ...arrB])]; // Union : uniques
let unionXl= [...arrA, ...arrB]; // Union : full list
// Symetrical difference (Union unique minus intersection):
let diff = arrA.filter(x => !arrB.includes(x))
.concat(arrB.filter(x => !arrA.includes(x)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment