Array methods

by kontrach

JavaScript

var numbers = [-5,-4,-3,-2,-1,0,1,2,3,4,5];

// FILTER METHOD
// To filter something use Array.prototype.filter method
var oddNumbers = numbers.filter( num => num % 2 === 0);

console.log('odd numbers are: ', oddNumbers);

// MAP METHOD
// To create new array of some parts of element of original array
var names = [{name: 'Denis'}, {name: 'Alexey'}].map( person => person.name);
console.log('names are: ', names);
// Or get array of changed values
var doubled = numbers.map( num => num * 2);
console.log('doubled are: ', doubled);

// SOME METHOD
// To check if at least one element of an array is match a condition
var atLeastOneIsString = [1,1,1,1,'str',1,1,1,2].some(el => typeof el === 'string');
console.log('has at least one string:', atLeastOneIsString);

// EVERY METHOD
// To check if every element of an array is match a condition
var areAllNumbers = [1,1,1,1,'str',1,1,1,2].every(el => typeof el === 'number');
console.log('all types are numbers:', areAllNumbers);

// Find METHOD
var denis = [{name: 'Denis'}, {name: 'Alexey'}].find(person => person.name === 'Denis');
console.log('Found person: ', denis);

// REDUCE METHOD
// The most powerfull method. get result of each iteration as accumulator
// a) sum digits in array
var sum = [1,2,3,4,5,6,7].reduce( (accumulator, nextValue, index, array) => accumulator + nextValue, 0);
console.log('sum is: ', sum);
// b) Combine map and filter functionality. We will add initial value of accumulator as an object.
// We will create objects with odd ids;
var obj = [1,2,3,4,5,6,7].reduce( (accumulator, nextValue) => {
	// is odd ?
  if ( nextValue % 2 === 0 ) {
  	// create prop of obj and fill in with new date;
  	accumulator['id' + nextValue] = new Date();
  }
  
  return accumulator;
  
}, {});
console.log('collected ODD ids are: ', obj);