Created
March 31, 2018 14:29
-
-
Save kuanhsuh/849b76a08b1a6233d02629c03b3ca689 to your computer and use it in GitHub Desktop.
Array Cardio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const users = [ | |
{ | |
id: 1, | |
name: 'Allison', | |
age: 4, | |
gender: 'female' | |
}, | |
{ | |
id: 2, | |
name: 'Derek', | |
age: 1, | |
gender: 'male' | |
}, | |
{ | |
id: 3, | |
name: 'Irene', | |
age: 35, | |
gender: 'female' | |
}, | |
{ | |
id: 4, | |
name: 'Danny', | |
age: 32, | |
gender: 'male' | |
}, | |
{ | |
id: 5, | |
name: 'Alin', | |
age: 25, | |
gender: 'female' | |
}, | |
] | |
// console.log('users', users) | |
// 1. forEach log each name | |
// users.forEach((user) => { | |
// console.log(user.name) | |
// }) | |
// 2. forEach 把每個user age 乘 2 | |
// users.forEach((user, index) => { | |
// return users[index].age = user.age * 2 | |
// }) | |
// console.log('users', users) | |
// map | |
// 3. log username | |
// users.map(user => console.log(user.name)) | |
// 4. 把每個user age 乘 2 | |
// let doubled = users.map((user) => { | |
// let tempObj = {} | |
// tempObj = {...user} | |
// tempObj.age = user.age * 2 | |
// return tempObj | |
// }) | |
// console.log('doubled', doubled) | |
// console.log('users', users) | |
// map won't change original array | |
// foreach will change original array | |
// Filter | |
// 5. 只要 age 低於 18 | |
// let kids = users.filter((user) => { | |
// let tempObj = {} | |
// tempObj = {...user} | |
// return tempObj.age < 18 | |
// }) | |
// 6. Only female | |
// let female = users.filter((user) => { | |
// let tempObj = {} | |
// tempObj = {...user} | |
// return tempObj.gender === 'female' | |
// }) | |
// console.log('female', female) | |
// Reduce | |
// 6. 把所有users 的年齡加起來 | |
let totalAge = users.reduce((acc, obj) => { | |
return acc + obj.age | |
}, 0) | |
// 0 + 4 = 4 | |
// 4 + 1 = 5 | |
// 5 + 35 = 40 | |
console.log(totalAge) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment