Skip to content

Latest commit

 

History

History
109 lines (78 loc) · 2.61 KB

00_3_intro_es2015.md

File metadata and controls

109 lines (78 loc) · 2.61 KB

es2015 or ES6

.map(), .reduce() and .filter()

.reduce()

myArray.reduce(callback[, initialValue])

It takes a collection of data and reduce it to a single value. It´s the base of one of the vital parts of Redux´s flow: reducers.

Example: reduce years collection into TOTAL years

const friends = [
  { name: 'Peter', age: 30 },
  { name: 'Tinkerbell', age: 100 },
  { name: 'Wendy', age: 31 }
];

friends.reduce((totalYear, eachAge) => {
  return (addFriendsAge = totalYear + eachAge.age);
}, 0);

console.log(addFriendsAge);
// 161

Short explanation... When we call reduce() we start from 0 (try changing 0 to 100). The first time our function is called, totalYear (or accumulator) will have the value of 0 and eachAge 30. The return of our function is a new variable (addFriendsAge) with the sum of all ages.

One comment about return. If we are returning in one line we can do...

renderMessage = message => message;

renderMessage = message => message;

...

render() {
	return (
		<div>{this.renderMessage('Hi')}</div>
	);
}

... or ... renderMessage = message => { return message; }; or the same, renderMessage = message => { return <div>{message}</div>; };

For multilines use ()

renderMessage = message => {
  return (
    <div>
      My message: <div>{message}</div>
    </div>
  );
};

.map()

const myArrayElements = myArray.map(function callback(currentValue[, index[, array]]) { // element to return }[, thisArg])

Given an array, it generates a new one (just for clarity allow me to repeat, new array) as the result of executing the callback function on each element of the array.

Example: map an array and retrieve a new array with the results assigned to a variable

const friends = [
  { name: 'Peter', age: 30 },
  { name: 'Tinkerbell', age: 100 },
  { name: 'Wendy', age: 31 }
];

const friendsNames = friends.map(eachFriend => eachFriend.name);

console.log(friendsNames);
// Array(3) [ "Peter", "Tinkerbell", "Wendy" ]

.filter()

var myArrayElements = myArray.filter(callback(element[, index[, array]])[, thisArg])

Given an array, it generates a new one with the elements that meet the criteria of the function logic.

Example: filter and retrieve all the elements which property name is NOT Wendy

const friends = [
  { name: 'Peter', age: 30 },
  { name: 'Tinkerbell', age: 100 },
  { name: 'Wendy', age: 31 }
];

const friendsFiltered = friends.filter(friend => friend.name != 'Wendy');

console.log(friendsFiltered);
/*
(2) […]
0: Object { name: "Peter", age: 30 }
1: Object { name: "Tinkerbell", age: 100 }
*/