View on GitHub

react

React[0] + Redux[0] > A brief introduction to React and Redux

es2015 or ES6

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

.reduce()

myArray.reduce(callback[, initialValue])

It takes a collection of data and reduces 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 }
];

const addFriendsAge = friends.reduce((totalYear, eachFriend) => {
  return totalYear + eachFriend.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 eachFriend.age 30. The return of our function is the running total, and reduce() itself returns the final accumulated value, which we assign to addFriendsAge.

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 }
*/