JavaScript Array Cardio Practice - Day 1 -
Вставка
- Опубліковано 1 січ 2017
- Today we sweat! In order to do the rest of the JavaScript30 exercises, we need to get really good at working with Arrays in JavaScript. Grab all the exercises and code samples at JavaScript30.com
- Наука та технологія
The Odin Project we grinding!
Yup.
Yes, we do.
@@user-ev8rn5yy6g Are you going to do fullstack javascript next?
@@avinash5715 yes, js is going to be next for me
@@avinash5715Yes
1) .filter(): 1:17
1.1) console.table(): 2:48
2) .map(): 3:55
3) .sort(): 5:16
4) .reduce(): 7:47
**Did this 'cause I come back constantly.
2 years later but I totally missed the console.table until reading this comment 🤝
Wow! And today I’m software engineer and UI designer. Thanks a lot wesbos! For you guys who are starting: you will succeed!
I have been coming back to this video whenever I get kinda stuck and especially this comment, every time I come back, I refresh my knowledge and it gets a little bit more cemented into my brain. Thanks!
10:08
I've just the started files and the exact same code, but instead of 523, I get 861.
It took me too long to realize that I have more people in my inventors. I'm going to post my comment in case someone else also has more inventors on their list and wonders why their answer is different too.
thank you!
thanks!
Exactly!
He has 7 entries and I (we) have 12 entries.
Dont worry about the results, worry about the stuff
Phew. Cheers
Here from the Odin Project. If you're having trouble understanding these, look at the documentation behind each method and really understand what its doing since he doesn't explain it in this video, he just explains what it does and how to use it. I spent 3 hours looking at the documentation for each one to truly understand the behind-the-scenes.
thanks bro
thanks will do the same!
can you please share the link to some documentation? thank you
@@aderonkelawal6452 just search for the functions and open the MDN articles
specially for reduce method and how to solve 8 exercise - it was nightmare.
I might be late to the party but I found your videos via the Odin Project. I really like that this gives me a few things to practice as I try and learn how to make JavaScript do what I want it to do.
same here im working on the Odin Project. although the problem with the link wont allow me to do the task eve when i copy and past the code
i share same feelings. i started odin project after wasting 4 years of not doing my best in my comp sci degree but here i am giving my all after i graduated. lets do this sir!!!!!!! also good luck to everyone who came this far because most just quit after a few lessons. its a marathon and not a sprint. we can do it. lessss goooo!!!!!!!!!!!!!!!!!!
@@marcofernstaedt8179 I had the same issue. I think my issue was from the
"links
.map
.filter" part of the code.
Amazing project, here you have the name theodinproject GIYF
I come from TOP too... How are you doing now?
5 years, and this video still invaluable, best content of javascript to learn array methods
That’s the beauty of JS fundamentals
congrats if you have made it this far in The Odin Project, a lot of people quit here as it gets harder keep going champ!
thanks buddy
hoping that you had completed the course
I am in the calculator almost, everything so far was hard, and now watching all these array methods, my brain cannot memorize everything, and how i will be able to think what i need for each action! Its literally impossible for someone coming with zero background in computer science and maths.. Any tips ?
@@youtubejproasters1224 experiment, if you have an idea. Go for it and explore it.
I was on the calculator as well. I asked lots of questions and experimented with my thought process and pseudocode.
Currently on the Todo List Project, almost done with it.
You got this
@@Overrunnerr I'm here from Odin Project! Hope you guys kept going. Every time it sends us to a video I notice fewer of us in the comments. I'm going to stick with it :)
@@chimpankie1954definitely should, I just finished my todo project not long ago and now I’m learning Asynchronous code.
I LOOOOOVE seeing you tighten up/reduce the size of the code. That is so freaking helpful.
This guy is brilliant, he is very talented but still feels how tough it is for beginners and showcases his coding for all levels. Doesn't give it the big I AM like a lot of programmers do but is humble and helpful to all. Bravo.
console.table!! Nice!!
This was the gem of the week for me.
true hahaha
"Bennington, Chester"
[starts crying]
These array cardio videos as a FANTASTIC IDEA! What a great concept to improve on the fundamentals! Would love to see more videos likes this!
you can solve more algorithms chalenges and sure you gonna reach his level
@@mohamedbaha-eddinebouzerou3269 Where?
For sorting the people by last name, since they have the last name first, just using people.sort() like that seems to work. It is nice to learn about splitting them up first and separating the specific parts to sort them.
Yeah, I was going to comment this as well. simply callig .sort() with no parameters does the job for this scenario.
The method outlined would be required if we were being asked to sort by first name, I suppose.
I am not familiar with the syntax used in the arrow function, either, where the variables `aLast` and `aFirst` are being declared. Looks like an array is being declared with two elements, but as a relative beginner, I wish this had been explained.
I found this specific one very confusing, to the point where i couldn't see how the people were sorted at the end even. Looked like the last names were still in a random order???
The reason this works is because a comma is U+002C, while the first unicode letter, A, is U+0041, which is numerically lower. This means that in the case of a shorter but otherwise identical name the decision isn't happening because of shorter length (which it should), but because the separator by chance is of a lower value than any letter a longer name could possibly contain, thus it gets sorted as if it were shorter. Of course, commas are common as separators, but one could absolutely use | or ¸ to do this and the whole thing would fall apart then
I'm barely keeping up with what's happening in this video but I'm very impressed by it all! I hope I can learn and master all these skills with time and practice!
instead of returning 1 and -1 you can also do this using,
// ordered list from oldest to youngest
const ordered = inventors.sort((a, b) => a.year - b.year);
console.table(ordered);
// sort by years lived
const oldest = inventors.sort(
(a, b) => b.passed - b.year - (a.passed - a.year)
);
console.table(oldest);
obligatory DRY remark, that you could/should use a pure function to find an age
e.g. getAge = (person) => person.passed - person.year;
returning 1 and -1 is kinda confusing to me yet i know how they works
@@c.0pium could you explain what are the meanings of 1 and -1? I just cant understand why returning them orders the array
@@carolinaserrano8267 from the documentation: with values (a,b) => ... if a is less than b a negative value should be passed, positive if otherwise. What this tells the sort() function is whether or not it should swap these two elements, and it will iterate over everything with that function until nothing moves anymore, i.e. the array is sorted as per the function's specification. What's happening under the hood is "bubble sort", essentially just this process of sweeping over an array and swapping 2 values if they're out of order, and sweeping over it again and again until nothing gets moved
Just wanted to say these video's are great! I'm only a few months into learning anything programming and this one in particular has really helped me understand Array methods, Thank-you! :)
like!! Im not lying nor exaggerating when I say that I indeed learned more of than what we are supposed to learn with this perfectly done video thanks to each of those single little extra steps you bother to quickly show to us. VERY important ones, regards!
The one working with information from Wikipedia was absolutely great. I felt nice doing it. Thank you
Your are Great and recommended by Steve Stiffith, most formidable javascript teacher. Thank you for doing all these for us.
this is just what I needed! Your way of explaining these subjects is great!
Thanks for the tutorial, i like when you use first function then when you make it arrow function, it makes it easy for beginners to follow and understand.
true
This challenge is just what I have been looking for!
As a beginner, I really hope to be on your level one day. You look like a Dev God from where I am sitting right now lol.
where are you at now?
@@ZakvonMammel I'm MILES from where I was when this comment was made, actually! I started my first job as a developer last month. These array methods are no longer a foreign language and I've become very comfortable using them. Reduce can still be annoying for me because of the accumulator if I remember correctly but yeah - night and day difference a year makes, haha.
@@Symuality That's awesome to hear!
reduce gives me some issues as well, so I think you're good there.
Do you still see him as a Dev God?
@@ZakvonMammel Ah God might be a little strong due to the way it kind of symbolizes some sort of idolization but Wes is DAMN good, that's for sure! He certainly seems as though he's put in the work and can write clean, efficient code!
@@Symuality Thanks for the replies! I bid you good, clean code on your journey :)
Another invaluable video. I'm really enjoying this 30 day JS course. With every video, i understand how things work in JS. Plus I learn much simpler and better ways to do things with JS. I cannot thank enough!😁
Thank you, Wes Bos. These practices help a lot in my learning journey.
Thank you so much!!!!!!!!!!! I screen-shotted each of the exercises to copy and practise in my own time..... I have been a bit overwhelmed by es6 probably because my javascript isn't yet rock solid
Loved the video.But loved even more what the people from odin project are commenting. They share what is being missed here and what to do about it with respect to the course.Thank you to all these peeps.Thats how a healthy community should be.
Love you Bos. You are the greatest teacher I've ever met. Truly. We appreciate your ability to spark the interest. Best regards!
I fond of the way you showing how to do things different ways also.
The problem I have with these is that I always find the other way to solve the same problems without those methods so it's hard for me to remember all those methods when I'm working on my personal projects.
Thanks for your work, Wes. I'm learning a lot.
Wow, Another seriously underrated JS tutorial. I also came here via Odin Project. Liked and subscribed. Thanks Wes Bos.
Quick question on outputting to the console... I used console.log() for both exercises #3 and #5 and when I do that, I get the same ordered list (incorrect for #3). However, when I change it to console.table(), I get the correct ordered lists for both problems (different answers). Why does log and table output different things? A little research tells me that it has something to do with console references, but I'm not fully understanding.. How do we know which one to use for debugging?
const inventors = [
{ first: "Albert", last: "Einstein", year: 1879, passed: 1955 },
{ first: "Isaac", last: "Newton", year: 1643, passed: 1727 },
{ first: "Galileo", last: "Galilei", year: 1564, passed: 1642 },
{ first: "Marie", last: "Curie", year: 1867, passed: 1934 },
{ first: "Johanne", last: "Keppler", year: 1571, passed: 1630 },
{ first: "Nicolous", last: "Corpenicus", year: 1473, passed: 1543},
{ first: "Max", last: "Planck", year: 1858, passed: 1947},
];
thx dude
Hot tip for young players
people.sort() works for 7. The default behaviour of sort() with no parameters is to sort by ASCII. Because the names Strings already start with the surname, literally all you need to do is use people.sort();
Also, for numerical sort, sort((a, b) => {return a - b}) works. Because if a is bigger, you return a negative number. If equal, you return 0. If smaller, you return a positive number.
This is all in the docs.
Hey friend, could you explain to me how did he accessed the DOM from wikipedia on his editor?.
Thanks for confirming my initial instinct. I was confused as to why the video went through all the trouble of splitting everything when all the names were already organized with the last name in the beginning.
Nice exercises! I was trying my own solutions before following along with yours. The reduce exercise is ambiguous about what it is asking for, however. The file asks to "sum up the instances of each of these." It might be more clearly worded as "return an object containing a key for each kind of vehicle with a value corresponding to the number of occurrences"
filter -> takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.
map -> used for creating a new array from an existing one, applying a function to each one of the elements of the first array
reduce -> deduct the array into a single solution, can return anything depends on the accumulator you have (either a number, an array or an object...)
sort -> arrange or reverse the original array based on the condition
These are all array method that would not change the original array, but return a new array or solution.
--> console.table is really nice way to show the data in console
i dont understand how he can get access to all the links from an external page using DOM around minute 12:00 can someone explain?
the querySelectorAll('a') loads all the links into the links variable.
at 10:04 I understood that total was equal to undefined... but did not understand how adding that 0 had the total initialized for it to start acumulating. Appreciate any help
with #6 i'm getting errors saying querySelector is 'null.' Im confused as to how you can grab anything from a link that's commented out?
I'm facing the same issue
7:11 "ternary" is actually a simpler word than you're thinking. It's just Turn-Ary. Very similar to canary (the bird).
Am I right in assuming that a lot of these variable names could be any value? (i.e. are we defining them as we use them?) Like, for example, we could have inventors.filter(person => (person.year >= 1500)) rather than 'inventor'. I only ask because I can't see 'inventor' defined anywhere and the code seems to work regardless of what I put in those brackets. Does JavaScript automatically assign each item in the array to that variable for the purpose of the function only?
the was awesome you're so efficient with your keystrokes my fingers were hurting a little trying to keep up without pausing too much.
7:39 The sort() by birthday part can be written without even using ternary operator like this: const ordered = inventors.sort( (a,b) => a.year - b.year )
Hands down one of the great teachers on JavaScript, now I understand why everybody I asked about who's course or material should I go for and everyone said 'Wes Bos'. Feeling lucky I found you and your courses.
Is someone can explain the .sort() method ? I don"t understand the return 1 and else -1 .
"sort inventors by birthdate, oldest to youngest" - keep in mind this means the lowest number (year) first, so ascending order.
also if the sort returns less than 0, sort leaves a, b unchanged, but if it returns greater than 0, it sorts b before a. so if number 1 is greater than number 2, it sorts number 2 before number 1, otherwise if number 1 is less than number 2, it leaves them be.
4 - 2 = 2; => sort 2 before 4.
2 - 4 = -2 => leave 2 before 4.
@Wes Bos Greetings, why is it that if(!obj[item]) {obj[item] = 0; } else {obj[item]++;}return obj; does returns items with count 0 in it??!!
full snippet:
let transport = cars.reduce((obj, item) => {
if(!obj[item]) {
obj[item] = 0;
} else {
obj[item]++;
}
return obj;
},{})
why am i getting a list with 0 counts where as without using "else" block it works just fine!!! Can anyone help with this??
Thanks y'all :)
Hi, i can't find the code samples on your website, can you help me with this please?
can someone explain to me why const can be used in the sort method, isn't is getting reassigned each time?
For number 3, the ternary operator I came with was a bit simpler, just "return a.year - b.year;" Is that going to cause any issues?
Awesome video incredibly helpful !! Currently doing the Odin Project and this was just incredible!
I have a problem with part 6 is not running links! it says caught undefined...! does anyone know the solution to that?
this was the next level content I needed for my javascript skills
glad to hear it!
16:27 Exercise 7:
I used const alphabetically = people.sort((a,b) => a>b);
Console logs the same output as yours, am I doing something wrong?
will using a ternary operator have an issue with type 2 errors returning false negatives when case a === b?
The Odin Project team, please keep going!
If you are coding along please pay attention that your total years lived might not match - that is okay, unlike the video the correct answer is 861 for your case(because the number of inventors have gone up in the code.)
Hello,
Can someone explain the returning -1 and 1 in the sort function. I'm still struggling to wrap my head around this.
for sort function you can also do: ((a,b) => {return a.year - b.year})
Can you please include the sandbox/file in the description so we can keep it as reference?
In the last task we don't need to create key with the value of 0 and then increase it to 1 at the second line. Just create it with 1 and put increment statement inside 'else' . Ternary is even simpler:
!obj[ item ] ? obj[ item ] = 1 : obj[ item ]++
I totally understand your videos, your speaking is very clear. Coming from TheOdinProject. Thank you so much for the content
At 11:06, why do we set -1 if lastGuy > nextGuy? I thought we set 1 if the criteria is met otherwise we set -1. So if the lastGuy lived longer, shouldnt we set 1?
For exercise 7, I did it slightly different. Is there anything wrong with the way I did it? Same results I think
let sortLastName = inventors.sort((a, b) => a.last > b.last ? 1 : -1).map(a => a.last +', ' + a.first)
Hi, great content as always!
I've a question about the exercize n.8: the solution in the video is not the same as:
console.log(people.sort()) ?
Or, if you want to create a new variable:
let alpha = people.sort()
console.log(alpha) ?
Then if you want to get rid off the comma you could use:
let newPeople = alpha.map((person) => {
return person.replace("," , "");
});
Is that another way we can get the same result?
The inventors object in the exercises contains 11 inventors now, looks like it was 7 when this was filmed.
At 10:01, why does adding the zero at the end change the result to what we want it to be? (The sum of the total years lived and not what it was before)
man.. just came back to this for review and that last one hit a new kinda way this time.. PSHH so helpful
Can somebody give me some info on the sort exercise 7, where he puts two variable names within square brackets ? I pretty much understood it, but some additional info won't hurt me.
For everyone saying he doesn't explain, yes he doesn't. Pause the video, go read about the method/function in the documentation, make stuff with what you have learned from it then start the video again, if you dont do this you wont learn. Also, shout-out to the Odin Project!
For #7, it still works if you remove everything within the sort method.
Maybe we should have sorted the first names.
tried the last sum up by myself first creating 5 different vars for each type of vehicle with a switch-case and then saw the obj implementation that you did.... atleast I'm learning
For #7, you can rewrite the code using the logical OR (||) operator to set a default value if the key doesn't exist in the object. If it doesn't exist, set its value to 0 then add one. Else, add one to whatever the value currently is.
const transportation = data.reduce((obj, item) => {
obj[item] = (obj[item] || 0 ) + 1;
return obj;
}, {});
console.log(transportation);
I have a question Wes. I hope you can help me out or any one else. If I have the streets array local, how do I do the same thing?
I tried:
let de = 'de ';
let newArr = streets.filter((street) => (street, de));
console.log(newArr);
but that only returns the same array. Any hints would be greatly appreciate. Thanks a million
NOTE: I figured it out:
const de = streets.filter((street) => street.includes('de'));
console.log(de);
Did CORS break exercise 6? Following the tutorial to the letter, the script bails with the following message: "Uncaught SyntaxError: redeclaration of const category"
What theme do you have on your VS code?
In number 4 why does putting a 0 at the end initializes total to 0 since total is the first item in the parameter list?
i still dont understand the 1 else -1 part from all examples. can anyone tell me why he is putting return 1 / -1 and why it is ordering it up or down?
Well explained and great video, thank you!
why is the result of my reduce function 861 and yours is 523
Don't worry, your result is correct. On the video Bos is using a little bit another array.
cool not only me
your answer is correct .the data in his array is limited
mine too
mine too lol
So hot examples! Thanks, Wes Bos! 👍 ✅
At function 7 why can I load first and last one , next one? Is it the name or the current name and next one?
Hey someone pls tell me what he does after 12 23 mean how he access that link page in dev tool i understand method application but cant able to understand what he does with that link
Thanks, man. Great job !!
on the reduce example, how come the value of total got initialized to 0 when we added it at the end of the function, how does that work behind the scene?
let yearsLived = inventors.reduce( (total, inventor) => {
return total += inventor.passed - inventor.year;
} , 0)
Had trouble on number 6 with:
const de = links
.map(link => link.textContent);
.filter(streetName => streetName.includes('de'));
It had an issue with "." I'm guessing from .filter? Any idea why it didn't work for me? Great video though!
This was very useful. Thank you so much!
i have a major crush on your code. I thought I already understood these methods, but I never wrote them the way you do.
@momoxiaoshizi another amazing playlist on functional programming in JS is: ua-cam.com/play/PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84.html
MPJ covers these methods and explains how they work so well!
... if you're interested.
at 12:30 the html structure has changed so I have two classes for that - mw-category mw-category-columns. But I can't get the links from them using const category = document.querySelector('.mw-category .mw-category-columns'); like he is.
document.querySelectorAll(".mw-category a")
full version:
let items = []; for(let item of [...document.querySelectorAll(".mw-category a")]) items.push(item.innerText);
console.log(items);
EDIT: you're doing it wrong, when HTML says class="a b" this means the item has both class a and b, when you say querySelector("a b") you're saying "give me all items of type b if they're children, direct or not, of an item of type a", also classes are specified as .class in CSS, without the dot it's a type. ".mw-category a" means all items of type a which are children of something classed as mw-category, if you querySelectorAll this you get all of the hyperlink elements which contain the names in innerText / innerHTML / textContent
For the sort compare functions, you can also just return a - b; (asc) or return b - a; (desc), instead of returning 1 or -1, correct?
Correct, it works for numbers.
for string too
yes.. but why? lol
Hey Wes great videos. Q's: what theme are you using in your editor?
17:50 How could we write const [last, first] = lastOne.split(', '); the regular ES5 way, without ES6 destructuring ? I don't know how to access all the arrays returned by split()... like var last = first_array_returned_by_split[0]; and so on... if that makes sense !
try console.log(parts);
its really a great video that make me understand the array function .
but when i playing with the functions i saw that the sort func affect the original array . and return the array but i dont know if its return a new array or passes a reference to the same array
why does " const oldest = inventors.sort (a.b) => { " on line 59 does not work
You inspired me to look up the pronunciation of Ternary operator:
ter-ner-e
why did u put 0 in the .reduce example to make it work?
6 years old and still a great cardio exercise
thank you so much,, love ur video series!
In 19:40 why did you have to use an arrow function instead of a proper function?
Great video! Just one doubt.
in the last exercise, why cant we use dot notation to change the values of the properties ?
obj.item++;
this does not work.
Edit : Went back to read the bracket and dot notations and found my answer. Since item is a variable, we can only use bracket notation to access a property with it.
Exactly. Only Bracket Notation can do that. I like that there’s always something to learn.
Hey Wes, I really dont get this one in the reduce function (No. 8)
"obj[item]"
What does it make exactly?
Thanks!
I know it was half year ago, but I had a problem too and came to the conclusion.
So obj is simply empty object, but item is "car", next interation "truck", next "van" etc.
So obj[item] for first iteration is obj["car"] which is nothing more than obj.car.
First it is undefined that's why if(!obj[item]) we create it. From obj = {} to obj = { car: 0 } then obj = { car: 1 } then
obj = {
car: 1,
truck: 0
} etc.
Here's a helpful link: javascript.info/object.
Read thru it til you get to the "square bracket" section or click that section on the left hand side.
@@tabloid64 thanks for explanation. If I understand it correctly, it's basically creating an empty object and initialize the key and value as {car: 0} or {car: 0, truck: 0} and increase the value as the reduce method iterates through each element in array??
@@davidkim5845 yes. in this case we have to specify more specifically with a booleon statemtnt though unlike the other reduce type example. if the key is not in that iteration we need to keep that value at 0 basically and not add anymore to that key. in the other example we just set an inital value of 0. since the initial value is in this example is technically just an empty object we need to THEN further specify how to organize the keys.