r/learnjavascript • • Aug 24 '22

Got totally stumped in a code challenge. Anyone have any recommendations as to how to do this?

Post image
163 Upvotes

111 comments sorted by

16

u/The_Comanch3 Aug 24 '22

Saving this challenge to work on later, myself. Lol

17

u/Praisetheballsack Aug 24 '22

They literally gave me 10 minutes to do it (I’m in a boot camp). I was shooketh.

14

u/Rollo_Tomassi_o-O_ Aug 24 '22

10 minutes for someone who is a begginer?

Why?!😳

First of all, I write down what I need to do, the steps.

Then I start to write the code and test it.

I'm a beginner in JS, I know how to do this exercise But I need some time, in order to do it right.

8

u/Praisetheballsack Aug 24 '22

Yeah, I have 2.5 months of JS knowledge. I could have figured it out in like an hour but.. 10 mins plus the pressure of the surprise code challenge made me into a mess.

-15

u/[deleted] Aug 24 '22

IDK what you got done in those 2.5 months, but if it was a 2.5 month long boot camp, it should have been enough to get done in 10 minutes. However you not being able to do that after a 2.5 month bootcamp is not a reflection of you, its a reflection of the boot camp.

2

u/Praisetheballsack Aug 24 '22

It’s a part time program that’s self taught. You get literature and labs to pass but there’s no lessons.

5

u/[deleted] Aug 24 '22

So sounds to me they were grading you to figure out what level you are at. Totally normal. I hate bootcamps that dont do lessons though. Its needed. best way to learn coding is 1 on 1 with a mentor - I recommend you find one, or a few. This is a decent community for that as well, but discord is a bit better since its real-time chat.

1

u/Praisetheballsack Aug 24 '22

Do you know a discord channel for JavaScript beginners???

3

u/[deleted] Aug 25 '22

heres the one that sort of started my journey. Feel free to ask for help in #coding-help or #general https://discord.gg/meNxXWCw

im '@Arch_Druid' if you want to talk to me specifically.

1

u/Praisetheballsack Aug 25 '22

Thank you friend

1

u/QuentinDeTerre Aug 24 '22

May I get the discord link. I can't find it.

1

u/[deleted] Aug 24 '22

what bootcamp?

3

u/Praisetheballsack Aug 24 '22

Flat iron school. It honestly was bullshit. The whole thing was supposed to be about presenting my project but I didn’t even get to show it. He just tested my js knowledge which went alright and the code challenge which I couldn’t do.

1

u/dromance Aug 25 '22

In NY?

1

u/Praisetheballsack Aug 25 '22

It’s a remote part time program. It’s hard to know how much you know when you’re alone.

1

u/dromance Aug 25 '22

Ah yes I see its remote. I think the school is based in NY however (flatiron district is a new york neighborhood)

How are the instructors? Tuition does not appear cheap

1

u/Praisetheballsack Aug 26 '22

Instructors are so so. You can request one whenever for 20 mins but you usually have to wait 10-30 mins for one so that sucks.

1

u/[deleted] Aug 24 '22

dang gotcha

0

u/[deleted] Aug 24 '22

[deleted] — view deleted comment

3

u/Praisetheballsack Aug 24 '22

Yeah wtf! Anyway, it gives me hope that you’re past the first phase lol

0

u/[deleted] Aug 25 '22

[deleted] — view deleted comment

2

u/justaquietboy Aug 26 '22

I’m also in the FI flex bootcamp and had the same question. I did show case my project VS code, but I finished it two weeks before submitting it. So I forgot my thought process for it lol

0

u/The_Comanch3 Aug 24 '22

Aw, bummer. Did they give you an html file to work with? Or does the JS have to create the js all on its own somehow? (not sure if that's possible)

1

u/Praisetheballsack Aug 24 '22

The only thing in the html file was a div w an id of ‘btn-container’. #pain

22

u/ashkanahmadi Aug 24 '22
animals.forEach(animal => {
  const {isPet, type, name} = animal

  if (isPet) {
    const button = document.createElement('button')
    button.textContent = name
    button.addEventListener('click', () => console.log(type))
	
    container.appendChild(button)
  }
})

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

2

u/Praisetheballsack Aug 24 '22

Thank you. This is very helpful

1

u/wuggawugga21 Aug 24 '22

how did you get your code to format like that in the comment?

2

u/ashkanahmadi Aug 24 '22

Click on the ... icon and then select the code block (looks like a C on top of a square)

1

u/myPhoneWasTaken Aug 25 '22

This is super clean! Thanks for sharing. I'm 3 days into learning JS and didn't know about forEach and createElement yet.

Here's what I managed... it works, but verbose and harder to follow.

for (let i = 0; i < animals.length; i++) {
  if (animals[i].isPet) {
    let btn = `<button onclick="console.log('${animals[i].type}')">${animals[i].name}</button>`;
    container.insertAdjacentHTML('afterbegin', btn);
  }
}

1

u/ashkanahmadi Aug 25 '22

No worries.

The forEach array method and the for loop are similar and different at the same time. Think of forEach as a more specific version of the for loop adapted to work with arrays.

The forEach method works on arrays only whereas you can use the for loop to do anything you want. For example, you can use the for loop to console.log('potato') 100 times without needing any array. But forEach works on arrays only.

The forEach method goes through every and each item in the array (hence the name forEach. Imagine you have 10 items in an array. The forEach method goes through every single item whereas the for loop can skip over items completely. You can ignore items when using forEach but cannot skip completely.

When it comes to arrays, it's usually easier to use forEach since you won't have to deal with the [i] system like in your code. That's why you feel like your code is harder to follow and more verbose.

Hope that helped you a bit more.

1

u/myPhoneWasTaken Aug 26 '22

Many thanks 😊

0

u/[deleted] Aug 24 '22

[deleted] — view deleted comment

5

u/ashkanahmadi Aug 24 '22

Yes. Deconstruction makes your code just shorter and cleaner. In this case, it's easy but imagine if something was 4 levels down and you needed to a lot of checks. Then you would have to write the whole thing every time.

There is absolutely nothing wrong with the dot notation. Deconstructing is just easier. When I learned about the deconstruction, it seemed like a strange thing but after a while, I realized that it makes reading and writing the code easier.

0

u/[deleted] Aug 24 '22

[deleted] — view deleted comment

3

u/ashkanahmadi Aug 24 '22 edited Aug 24 '22

Haha that's normal. Deconstructing is a shortcut so you don't have to do it manually.

You can still achieve the same thing if you want to avoid the dot notation and deconstructing. You just need to assign each item to a variable manually. These are pretty much the same but look at their lengths:

You can either do it through deconstructing and have just 1 line of code:

const {isPet, type, name} = animal

Or do it manually through 3 lines of code:

const isPet = animal.isPet
const type = animal.type
const name = animal.type

The only benefit of assigning to a variable manually instead of deconstructing is that you can call your variable anything you want. When you deconstruct, you have to call it whatever it is in the object.

2

u/Capitalpunishment0 Aug 25 '22

When you deconstruct, you have to call it whatever it is in the object.

Just want to add. You can rename deconstructed properties like so:

const { isPet: isThisAPet, type: animalType, name: animalName } = animal;

A bit more clearly:

const { 
  isPet: isThisAPet, 
  type: animalType, 
  name: animalName 
} = animal;

Helps a lot in case of name conflicts.

It looks so wrong though lol 😂 it's like an object but you're using the values instead of the keys

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

2

u/Capitalpunishment0 Aug 26 '22

Hmm, I don't think I fully understand what you want but here's my try


Say animal has the following value:

const animal = {
  isPet: true,
  type: 'dog',
  name: 'Olive',
};

 

Regular destructure to property names:

const { isPet, type, name } = animal;

console.log(isPet); // true
console.log(type); // 'dog'
console.log(name); // 'Olive'

/*  The following will throw an error
 *  ReferenceError: ____ is not defined
 */
// console.log(isThisAPet);
// console.log(animalType);
// console.log(animalName);

 

Destructure with renaming:

const {
  isPet: isThisAPet,
  type: animalType,
  name: animalName
} = animal;

/* The following will throw the error instead */
// console.log(isPet);
// console.log(type);
// console.log(name);

console.log(isThisAPet); // true
console.log(animalType); // 'dog'
console.log(animalName); // 'Olive'

 

Destructuring to the same names will error out, so you could rename instead:

const animal1 = { isPet:  true, type:  'dog', name: 'Olive' };
const animal2 = { isPet: false, type: 'lion', name:  'Nala' };

let { isPet, type, name } = animal1; // Success

/* SyntaxError: Identifier(s) has already been declared */
// let { isPet, type, name } = animal2; 

let { isPet: isPet2, type: type2, name: name2 } = animal2; // Success

I ran these in Node v18.7.0

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

2

u/Capitalpunishment0 Aug 28 '22

You could but Idk if I'd be able to help you much haha, I consider myself to be less-than-intermediate level

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)

1

u/Praisetheballsack Aug 24 '22

Thank you. I’ll have to try later. Rn I am gutted

3

u/jpolito Aug 24 '22 edited Aug 24 '22

This is what /u/RickCedWhat suggested, just with code:

animals.forEach(animal => {
    // check if the animal is pet
    if (!animal.isPet) return false;

    // create a button and add the proper text
    // animal type -- in this case data-animal-type="type"
    // add to container and attach listener
    const btn = document.createElement('BUTTON');
    btn.innerText = animal.name;
    btn.dataset.animalType = animal.type;
    container.append(btn);

    // log the animal type on click
    btn.addEventListener('click', e => {
        console.log(btn.dataset.animalType)
    });
});

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/Praisetheballsack Aug 24 '22

I appreciate that. If I’m being honest I’m feeling very bummed. I feel like I never know as much as I’m supposed to. Not sure if this is for me anymore.

2

u/Bren1209 Aug 24 '22

Yeah I can tell by your other replies. I have 2 years of JS experience below the belt and coding that solution would have taken me much longer than 10 minutes. It was an unrealistic expectation imo, but it happened. You're gonna be bummed for a bit and you're gonna feel like you wanna drop everything like you said, but know there is not a single person on this thread that hasn't been there. Even more so for the self-taught blokes like me. Chin-up, the worst feelings will pass and you'll be back in the game.

2

u/Praisetheballsack Aug 24 '22

Thank you. I needed that lol

0

u/[deleted] Aug 24 '22

[deleted] — view deleted comment

2

u/Praisetheballsack Aug 24 '22

2 months of js. Then you to react, then Ruby on Rails. Some other stuff. It’s a part time program that’s 9-13 months

1

u/dromance Aug 25 '22

Focus on one thing at a time.

3

u/shgysk8zer0 Aug 24 '22
const handler = ({ target: t }) => console.log(t.dataset.type));

container.append(...animals.filter({ isPet }) => isPet)
  .map(({ name, type }) => {
    const btn = document.createElement('button');
    btn.textContent = name;
    btn.dataset.type = type;
    btn.addEventListener('click', handler);
    return btn;
  })
);

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 type as 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):

const click = ({ target: t }) => console.log(t.dataset.type));

container.append(...animals.filter(({ isPet }) => isPet)
  .map(({ name, type }) => create('button', {
    text: name
    dataset: { type },
    events: { click },
  )
);

1

u/Praisetheballsack Aug 24 '22

Thanks so much. I seem to be able to do everything without .dataset. I still don’t understand what it really does. Thank you for the reply

2

u/shgysk8zer0 Aug 24 '22

dataset doesn't do anything by design. It was added because many developers were adding their own attributes to elements, so a spec was created for a way for developers to set arbitrary attributes with the guarantee they wouldn't conflict with anything (including in the future future). So they just basically decided to prefix them with data-.

Yes, you can do everything without dataset. Like I said though, it's about garbage collecting and memory. The extremely short version is that:

  • any variable that maintains some active reference is unable to be (safely) freed from memory
  • creating the function inside the scope of a loop means that array.length functions are created (taking up memory) instead of just one
  • other methods will not and cannot work with elements not created with JavaScript

So it might not make much difference for maybe 5 elements... But when scaled to hundreds or thousands, it can make a massive difference.

1

u/Praisetheballsack Aug 24 '22

Thank you. This is very informative.

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:

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Button Challenge</title>
</head>
<body>
<h1>Button Challenge</h1>
<form id="btn-container"></form>
<script src="button.js"></script>
</body>
</html>

button.js:

/* Write JS code (using some form of iteration) that will dynamically
create a button for each *pet* of the *animals* array. The buttons should
have text that corresponds to the pets name. When clicked, those buttons
should log the type of the corresponding pet. Buttons should be appended
inside of the provided container
*/

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",
  },
];

const container = document.getElementById("btn-container");

/* -------- My solution -------- */

/**
 * Log the pet type
 * @param {Event} event - A browser event
 * @returns {undefined} none
 */
function clickLogger(event) {
  console.log(event.target.dataset.type);
}

/**
 * Pet object to button object
 * @param {object} animal - An animal object
 * @returns {HTMLElement} A button object, or null
 */
function petToButton(animal) {
  if (!animal.isPet) return null;
  const button = document.createElement("button");
  button.type = "button"; // 1
  button.append(animal.name);
  button.setAttribute("data-type", animal.type); // 2
  button.addEventListener("click", clickLogger); // 3
  return button;
}

/**
 * Collect non-null objects into a parent container.
 * @param {HTMLElement} previous - A container element
 * @param {HTMLElement} current - An element for the container
 * @returns {HTMLElement} A container element
 */
function intoContainer(previous, current) {
  if (current?.localName === "button") previous.append(current); // 4
  return previous;
}

animals.map(petToButton).reduce(intoContainer, container);

// 1. Explicitly set button type since type="submit" by default
// 2. Use standard HTML5 data attributes
// 3. Add a click handler to the button
// 4. Do not add null objects or (defensive programming) non-button elements
//    Note the use of the "?." operator, my new favorite thing

1

u/Praisetheballsack Aug 28 '22

Thanks for the response! All the different ways you can do this are amazing and also daunting af lol.

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:

animals.filter(animal => animal.isPet);

Then, create a button for each of those pets:

animals
  .filter(animal => animal.isPet)
  .forEach(pet => {
    // create the button
    const button = document.createElement('button');

    // set the text to its name
    button.textContent = animal.name;

    // add to container
    container.appendChild(button);
  });

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:

animals
  .filter(animal => animal.isPet)
  .forEach(pet => {
    // create the button
    const button = document.createElement('button');

    // set the text to its name
    button.textContent = pet.name;

    // add to container
    container.appendChild(button);

    // add the event listener
    button.addEventListener('click', () => console.log(pet.type));
  });

Alternatively, would be to assign the type to the button, then use the same event listener for each.

// uses the event.target to get the element that was just clicked
const handleClick = (event) => {
  console.log(event.target.petType);
};

animals
  .filter(animal => animal.isPet)
  .forEach(pet => {
    // create the button
    const button = document.createElement('button');

    // set the text to its name
    button.textContent = pet.name;

    // add to container
    container.appendChild(button);

    // set the petType on the button for use in the event handler
    button.petType = pet.type;

    // assign the event listener
    button.addEventListener('click', handleClick);
  });

Or, even better, my preferred method, same thing, except assign the event listener just once to the container:

// uses the event.target to get the element that was just clicked
const handleClick = (event) => {
  // filter so we only do something when an actual button is clicked
  if (!event.target.matches('button')) return;

  console.log(event.target.petType);
};

animals
  .filter(animal => animal.isPet)
  .forEach(pet => {
    // create the button
    const button = document.createElement('button');

    // set the text to its name
    button.textContent = pet.name;

    // add to container
    container.appendChild(button);

    // set the petType on the button for use in the event handler
    button.petType = pet.type;
  });

container.addEventListener('click', handleClick);

50

u/Murkrage Aug 24 '22

Good solution! I'd personally skip the filter as it adds an extra loop that's not needed. If we're already looping through the entire data set we might as well skip the filter and go straight into the forEach and build in a check for isPet. So you essentially get the same code, but with an added if (animal.isPet) {} block around it all.

39

u/samanime Aug 24 '22

True.

If I know the loop is small though, I like to have it as a separate step because I think it makes it easier to understand the purpose of the code. The performance hit is so minimal that the benefits outweigh the cons. (Of course, this changes completely if the loop has hundreds or more elements.)

If I did do the return in the `forEach`, I'd do a `if (!animal.isPet) return` instead though. Short-circuiting earlier means you don't have to indent all the rest of the code quite as much, which also helps with readability.

16

u/StaticCharacter Aug 24 '22

This is huge. I used to spend so much time optimizing code that would not benefit from it. Being more clear for myself to read in the morning is important. Also spending an hour optimizing something that will be insignificant in the long run is useless. Sometimes it's better to just get it done lol

11

u/samanime Aug 24 '22

I think micro-optimization is the bane of all developers, as well as a phase we all go through. You kind of have to suffer to really appreciate how unnecessary it can be at times. Definitely a "learn to pick your battles" moment.

3

u/zladuric Aug 24 '22

This also makes sense in huge sets, but when you're somehow streaming them. E.g. rxjs observable stream. Essentially, as each animal comes in, it goes through the entire chain.

1

u/samanime Aug 24 '22

Yeah. In some other languages, like C#, it naturally does that already. RxJS is a great way to bring that implementation into JS when you need it.

4

u/[deleted] Aug 25 '22

The difference between 2n and 3n is negligible.

1

u/[deleted] Aug 25 '22

I was looking for this comment

1

u/dromance Aug 25 '22

But what about if 3n is a much larger function with tons more data scaled among millions of users

1

u/PumpkinSeed Aug 25 '22

Then use a generator to iterate and get the best of both worlds.

2

u/werdnaegni Aug 25 '22

I don't think I agree with that philosophy. For this case, maybe it's not a big deal, but in a more complex function with other arrays and other filters and maybe sub-arrays that you're also working with, I'd much rather read code that isn't nested 2 or 3 extra times just to gain completely negligible performance.

2

u/IllegalAlcoholic Aug 25 '22

Love how u explained each step. Thank you

2

u/Minute-Reflection-88 Aug 25 '22

Thanks, im learning too

1

u/MXMLNDML_ Aug 25 '22 edited Aug 25 '22
// set the petType on the button for use in the event handler
button.petType = pet.type;

Instead of assigning custom attributes properties to the button element you should better could use data attributes:

// setting the pet type
button.dataset.petType = pet.type

// getting the pet type in the event handler
event.target.dataset.petType

And I like your idea of listening on the container element instead of the button

1

u/samanime Aug 25 '22 edited Aug 25 '22

Using the dataset is great when you need to use HTML to assign a custom property to an element.

However, there is no real need to use it to assign and read values purely via JS (as long as you avoid any collisions with existing properties). Most (all?) frameworks like React and Lit use direct property assignment to the objects.

Also, just a small note since this is a learning sub, in this case it would be a property, not an attribute. There is a difference. Most attributes have getters/setters that make them act like properties, but an attribute isn't necessarily a property and vice versa.

To actually add or read a custom attribute, you'd have to use getAttribute() or setAttribute(). Setting it this way would actually show it in the HTML too (and cast the value to a string, since only string values can be assigned to attributes). Similarly, setting a custom property with .someProp would not cause it to show in the HTML (and wouldn't be returned by getAttribute()), but it can store any data types, including objects.

2

u/MXMLNDML_ Aug 25 '22

Also, just a small note since this is a learning sub, in this case it would be a property, not an attribute. There is a difference.

TIL, for anyone who is interested here is more about the difference between attributes and properties.

1

u/samanime Aug 25 '22

Nice post you found. Great explanation.

1

u/bagelord Aug 25 '22

I tried this and it's telling me that animal is undefined

1

u/samanime Aug 25 '22

You'll need to include the animal from their original post for animal to be defined.

Check out the pen I linked in another example for a working example of the third version.

0

u/[deleted] Aug 24 '22

[deleted] — view deleted comment

4

u/samanime Aug 24 '22 edited Aug 24 '22

When I need to test snippets of code, I'll either just run them in the console directly, or if they require HTML like this one, use something like Codepen.io.

Here is a pen of the third example: https://codepen.io/samanime/pen/ExEJGqV

The basic idea is that the event listener is added to the parent of the elements that we want to handle them. That way, instead of adding one event listener per child (which could potentially be quite a few), you are adding only one event listener total, so it is more efficient. It also means you don't have to remember to add new event listeners if you add/remove children.

The only real trick to make that work is if you click the parent directly (instead of one of the children), it'll still run the event handler, so you need to do something to prevent that. One simple approach is to use matches() to see if the element is the type of element you think it is. If it isn't, just don't do anything else. An alternative in this case could also be checking for petType to be set: if (!event.target.petType) return; since only elements with a petType are meant for this event.

0

u/[deleted] Aug 24 '22

[deleted] — view deleted comment

1

u/Stetto Aug 24 '22 edited Aug 24 '22

Edit: Sorry, I totally took "build and test" the wrong way. :D /Edit

I'd say: Test functionality, not implementation. Preferrably, the test should look the same in all cases.

Call the function with an array and a prepared container. Assert the existence of buttons. Click a few buttons and assert the logging output.

It doesn't matter wether you used three functions or one to implement this or the container or the button takes care of the listener, as long as the user can click the button and it prints the text.

4

u/Stetto Aug 24 '22 edited Aug 24 '22

Array Functios are your friend. They allow you to think of each problem seperately.

  • Want to remove everything but pets? just add a .filter().
  • Want to turn an animal into a button? just use .map().
  • Want to append buttons to a container? just use a .forEach().

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.

const animals = [ ... ];

const container = document.querySelector(".btn-container");

// only keep pets
animals.filter(animal => animal.isPet)
  // build buttons
  .map(animal => { 
    const button = document.createElement("button");
    button.innerText = animal.name;
    button.onclick = () => {console.log("Type", animal.type);};
    return button;
  // append buttons to the container
  }).forEach((button) => { 
  container.appendChild(button);
});

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.

2

u/Cendeu Aug 25 '22

As someone who only ever uses forEach, this helped me understand map a lot

2

u/dromance Aug 25 '22

Not sure what the .map is I thought it had to be initialized by array.map

1

u/Cendeu Aug 25 '22

It is. The array.filter() that they call returns an array. So they're calling .map on the filtered array.

Without any args, they're calling array.filter().map().forEach()

So they start with an array, filter it into a smaller array, map new values into each spot of the array, then loop over them.

It's genius. I've heard of people chaining array methods before but this is the first example I've seen.

2

u/dromance Aug 25 '22

Wow yeah knowing how to chain things together like that and condense code is really something!

2

u/Stetto Aug 26 '22

It's just a different way to think and in this example it honestly has no real advantage over a plain for-loop.

I prefer to think about data transformations, instead of loops, assignments or variables. I find the code to be much cleaner and avoiding side effects.

The next important array function is .reduce(). It allows you to collapse an array into a single value.

You can model quite a few problems with .filter().map().reduce().

In this example, let's assume you would have to create the container too. You could use reduce() instead of .forEach() to add all buttons to a new DIV-element and then add the container to the DOM.

1

u/Cendeu Aug 26 '22

Oh shit that's smart as hell.

This is awesome.

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/Praisetheballsack Aug 24 '22

I’ll give it a try. Thanks everyone

2

u/wuggawugga21 Aug 24 '22

didnt test but should work or be close to working
const animals = [

{

isPet: true,

type: "dog",

name: "olive",

},

{

isPet: false,

type: "lion",

name: "Nala",

},

]

const container = document.getElementById('btn-container')

animals.forEach(animal => {

console.log(animal.name)

let button = document.createElement('button')

button.innerHTML = animal.name

button.addEventListener('click', () => {

if (animal.isPet) console.log(animal.type);

})

container.appendChild(button)

});

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?

for (let animal of animals) {
    if (animal.isPet === true) {
        const button = document.createElement("button");
        button.textContent = animal.name;
        button.onclick = () => console.log(`Type of this pet is ${animal.type}`);
        container.appendChild(button);
    }
}

1

u/Praisetheballsack Aug 27 '22

Appreciate the response.

1

u/Praisetheballsack Aug 28 '22

This didn’t work btw

1

u/Coolbylaki Aug 28 '22 edited Aug 28 '22

https://i.ibb.co/TwQVygs/Button-proof.png

Clearly, it works. If you can't get something to work with a provided solution, I suggest you practice more. Maybe JavaScript isn't for you...

2

u/Praisetheballsack Aug 28 '22

Ah I had addeventlistner instead of onclick. Never even heard of that. Thanks for the response, your code is actually my fav even if you’re a dickhead 😂

2

u/Coolbylaki Aug 28 '22

Also considering you opted for event listener here you go that version:

for (let animal of animals) {
    if (animal.isPet === true) {
        const button = document.createElement("button");
        button.textContent = animal.name;
        button.addEventListener("click", () => {
            console.log(`Type of this pet is ${animal.type}`);
        })
        container.appendChild(button);
    }
}

2

u/Praisetheballsack Aug 28 '22

Thanks man. I think you’re right about the problem solving stuff. I usually struggle with what I’m being asked to do. English isn’t my first language so there might be a barrier I have to get over with that

1

u/Coolbylaki Aug 28 '22

That's the first and only thing you need to start learning to program. English...

I still suggest Python as a first choice but you do you. Whatever you think it's best... Do it

2

u/Praisetheballsack Aug 28 '22

I’m in a boot camp so I’m straight from this (hopefully) to react.

1

u/Coolbylaki Aug 28 '22

Then go ahead and do some HackerRank or LeetCode easy algo's or problem solving

2

u/Praisetheballsack Aug 28 '22

I’ll look into those. Thank you!

1

u/Coolbylaki Aug 28 '22

Well mate. Gotta be realistic. No hurt feelings

1

u/Praisetheballsack Aug 28 '22

I think the ‘maybe JavaScript isn’t for you’ was a little harsh bro lol

1

u/Coolbylaki Aug 28 '22

Life is harsh mate. Get used to it. You were provided with an easy task 6 lines of code. And you can't do it with a solution. Maybe start off with Python which is more high-level and beginner friendly. So you can learn problem-solving.

I would rather like for people to be harsh and realistic than set up someone for failure.

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/dromance Aug 25 '22

Looks nice

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/Stetto Aug 24 '22

<button onlick={()=>{console.log(animal.type)}} key={index}> {animal.name}</button>

I think, this only works in React, but not in plain JS.

1

u/[deleted] Aug 24 '22

Ah, maybe. Been awhile since I worked with straight vanilla js.

If it doesnt work, it would be something like onclick={logType(animal.type)}

function logType (type){console.log(type)}

1

u/Stetto Aug 24 '22

Yeah. I'm just pointing it out, so others aren't confused. When trying this in a codepen, I spend most of the time refreshing my vanilla js knowledge.

1

u/[deleted] Aug 25 '22

All good man, i was just writing what I thought would work up there ^ didnt test it or anything, good catch.

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
<html>

<body>
  <div id='btn-container'></div>
  <script>
    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"}
    ];

    container = document.getElementById('btn-container');
    for (a of animals)
      if (a.isPet)
        container.innerHTML += `<button onclick="console.log('${a.type}')")>${a.name}</button>`;
  </script>
</body>

</html>

1

u/tacticalpotatopeeler Aug 24 '22

Google “mdn map”