Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tgmarinho/f1a145d7c7c87fc495181ba21cf3681f to your computer and use it in GitHub Desktop.
Save tgmarinho/f1a145d7c7c87fc495181ba21cf3681f to your computer and use it in GitHub Desktop.
Practicing Arrays, ForEach, Map, Filter and Reduce!
// Complete the below questions using this array:
const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},
];
//Create an array using forEach that has all the usernames with a "!" to each of the usernames
const newArrayForEach = []
array.forEach(user => {
newArrayForEach.push({ ...user, username: `${user.username}!` })
})
// Just iterate on array, that is why I create another array.
//Create an array using map that has all the usernames with a "? to each of the usernames
const newArrayMap = array.map(user => ({ ...user, username: `${user.username}?` }))
// when you return an array of objects, then you should put ({ }) for return the object to array.
//Filter the array to only include users who are on team: red
const onlyTeamRed = array.filter(user => user.team === 'red')
// Filter returns an array of items filtered of course.
//Find out the total score of all users using reduce
const totalScore = array.reduce((acc, user) => acc.score + user.score, 0)
// How it is a sum of values, so the first value should be a number valid like 0
// (1), what is the value of i?
// (2), Make this map function pure:
const arrayNum = [1, 2, 4, 5, 8, 9];
const newArray = arrayNum.map((num, i) => {
console.log(num, i);
alert(num);
return num * 2;
})
// check it out:
const newArray = arrayNum.map(num => num * 2)
//BONUS: create a new list with all user information, but add "!" to the end of each items they own.
const anwser = array.map(user => ({...user, items: user.items.map(item => `${item}!`)}))
@khankluan24
Copy link

Love

@khankluan24
Copy link

I have tested that the exercise"Find out the total score of all users using reduce" was wrong that acc is exactly accumulator, which is a number so that we can't add it with a property like score, so acc.score ==> acc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment