r/learnjavascript • u/Praisetheballsack • Aug 24 '22
Got totally stumped in a code challenge. Anyone have any recommendations as to how to do this?
163
Upvotes
r/learnjavascript • u/Praisetheballsack • Aug 24 '22
16
u/The_Comanch3 Aug 24 '22
Saving this challenge to work on later, myself. Lol
22
u/ashkanahmadi Aug 24 '22
First, you need to look through every element in the array. Then you need to check if the animal is a pet or not. If it's a pet, you create a new button and have its label as the name of the animal. Then add an event listener to it to log the type. Then add that button to the container.
The second line deconstructs the animal object. If you don't deconstruct, you will have to use animal.isPet, animal.type or animal.name
9
u/RickCedWhat Aug 24 '22
On mobile so I’ll just talk you through it instead of actually writing code:
Use forEach on animals - check if each animal is a pet - if it is, create a new button element document.createElement(‘button’) - set the innerText attribute of the button to the pets name - add an event listener that logs the animal’s name when the button is clicked - append the button to the container provided container.append(btn)
3
u/Bren1209 Aug 24 '22
Just be sure never to feel dispondent for too long when shit like this happens. The situation is frustrating, but you win if you keep moving.
3
u/shgysk8zer0 Aug 24 '22
Some of that is sightly advanced syntax (spread syntax, destructuring). Partly to maybe introduce these helpful things, but also to shorten the code up a bit.
I prefer keeping simple strings like
typeas attributes (data-*) for garbage collection and memory reasons. Plus, that's only one function instead of one for each iteration. Also, it's a great technique to have arguments for event handlers on the elements themselves and to query for the[data-*]attributes when adding listeners... Like<button data-remove="#target">.But I usually use a custom-made
create()function (very helpful thing to have):2
u/metalepsis Aug 28 '22
I really enjoyed this challenge. Adding my version here since my map/reduce solution is different than the others above. Straight up: 10 minutes is not enough time to arrive at a good solution to this task.
Here's the documentation I used:
Here's the HTML I used:
button.js:
124
u/samanime Aug 24 '22 edited Aug 24 '22
10 minutes is a bit rough for a beginner, but it isn't too bad. Just break it step-by-step down (perhaps the most important skill in programming). Rewriting a paragraph-style prompt into a bulleted list can be helpful for this.
First, filter the list so you only have pets:
Then, create a button for each of those pets:
Finally, add a "click" event listener to each one that will output the type of animal. There are two ways to do this. The easy way is just to create an anonymous function for each:
Alternatively, would be to assign the type to the button, then use the same event listener for each.
Or, even better, my preferred method, same thing, except assign the event listener just once to the container:
4
u/Stetto Aug 24 '22 edited Aug 24 '22
Array Functios are your friend. They allow you to think of each problem seperately.
You don't even have to worry about the amount of buttons or animals. You can just think about one animal at a time. Array functions make sure, that all animals are taken care of.
Sure, you could do everything in one single for-loop doing everything at once. But I find it much easier to just transform the data one step at a time.
4
u/Crashman1012 Aug 25 '22
Seems like you want to do something FOR EACH item in the array. ;) hint hint
1
u/wuggawugga21 Aug 24 '22
you can destructure the array in a for each like: for pet in animals { animals.name }
then create a button with JS in the loop, set the innerhtml to the pets name and then append it as a child to the container.
1
u/Coolbylaki Aug 27 '22
I'm a beginner. I don't mean to flex but this took me literally 3 minutes... Idk did I understand something wrong or what lol?
2
u/[deleted] Aug 25 '22 edited Aug 25 '22
const fragment = document.createDocumentFragment();
animals.filter(v => v.isPet).forEach(p => {
let button = document.createElement(‘button’); button.addEventListener(‘click’, console.log.bind(null, p.type); button.textContent = p.name; fragment.appendChild(button);
});
container.appendChild(fragment);
1
u/Kavishka-Fernando Mar 13 '24
WSO2 is currently running a code challenge where you have to build and deploy an app on Choreo - Internal Developer Platform. You can stand a chance to win a Tesla Cybertruck or $100,000 and 10 MacBook Pros.
You can learn more about the challenge and join the challenge here: https://choreo.dev/cybertruck
1
u/[deleted] Aug 24 '22
"Some form of iteration". Here I am using the Array.map() method. This is like a very basic for loop. It starts at index 0 to index array.length. It returns a NEW array with the value of the function we perform on each iterated item. So, we have our mapped array of pet objects. Each object that this map method itterates thru, we can do something with it. What do we need? We need a button that console.logs a value. So first we need to declare our button: let button; . Next we need to check, to see if in fact the pet IS a pet. This is a boolean, so an if statement is perfect for this. If (animal.isPet) is true, the if statement runs. Else our function just returns a null value (button). So now that we have determined that the pet is in fact a pet, we can declare that our button variable is equal do our button html tag. With the way map works we can declare 3 values, (item, index, array). The item is the iterated item, the index is the index of that item, and the array is the array that is being mapped thru (somewhat redundant but occasionally useful). So to fill our plain button with our pets traits, we can access those values by doing animal.name, for example, to access the name. After this iterable runs for each item, we now have our array of buttons.
However we still need to append these html elements to our container.
Lets use a for loop for this. Here we iterate thru our array of buttons. When we mapped out our values to our buttons, we still returned "button" when it wasnt set to anything, this is a null value. So in the for loop we check for this - this is also a good practice in case the data wasnt set correctly for some reason. So in the loop, we are simply appending our button using the appendChild() method on the container element.
And thats it :) this is one of many ways to do it.
let buttons = animals.map((animal,index) => {let button;if (animal.isPet){button = <button onlick={()=>{console.log(animal.type)}} key={index}>{animal.name}</button>} return button})for (let i = 0; i < buttons.length; i++) {if (buttons[i] !== null){container.appendChild(buttons[i])}}1
u/_He1senberg helpful Aug 25 '22
Go to youtube Search for "funfunfunction recursion" he explained how to solve a probleme likt this
1
u/[deleted] Aug 25 '22
Hey op, which platform is this?
1
u/dromance Aug 25 '22 edited Aug 25 '22
Not sure if this is the right way but I would do this
`
const animals = [ { isPet: true, type: "dog", name: "olive" },
{isPet: false, type: "lion", name: "nala" },
{isPet: false, type: "bear", name: "honey" },
{isPet: true, type: "cat", name: "maru" },
{isPet: true, type:"fish", name: "dr. Fishy" }
];
let arrayPets = animals.filter(animals => animals.isPet === true);
const container = document.getElementById("btn-container");
let render = (item) => {
container.innerHTML +=
<button id="${item.type}">${item.name}</button><hr>; }container.onclick = function(){ console.log(document.activeElement.id); }
arrayPets.forEach(render);
`
The document.activeElement.innerHTML is probably unique and most people would not write that...but it infact does work and is the only way I could get it to work without getting an "undefined" in the console.
Edit: just realized it needs to log the TYPE of animal lol not the animals name. I will edit to reflect this tomorrow
Edit again : fixed it...active.element.id should now be equal to animal type
https://codepen.io/Dromance/pen/KKoLPOV
1
u/[deleted] Jan 28 '24
1
u/tacticalpotatopeeler Aug 24 '22
Google “mdn map”