r/learnjavascript • u/192_168_1_x • May 29 '21
Really helpful illustration of JS array methods
21
u/NickHack997 May 29 '21
I really like this illustration it's simple and easy to understand!
I didn't know about fill, but looking at the docs from MDN you need to flip the arguments, value is always first.
22
u/FatFingerHelperBot May 29 '21
It seems that your comment contains 1 or more links that are hard to tap for mobile users. I will extend those so they're easier for our sausage fingers to click!
Here is link number 1 - Previous text "MDN"
Please PM /u/eganwall with issues or feedback! | Code | Delete
17
4
2
u/Urbantransit May 29 '21
Good bot
2
u/B0tRank May 29 '21
Thank you, Urbantransit, for voting on FatFingerHelperBot.
This bot wants to find the best and worst bots on Reddit. You can view results here.
Even if I don't reply to your comment, I'm still listening for votes. Check the webpage to see if your vote registered!
1
2
u/TalonKAringham May 30 '21
I’ll be honest, I still have no clue what .map() does?
5
u/LakeInTheSky May 30 '21
It basically transforms every element of an array according to a function you pass as an argument. It won't modify the original array, but it will return another array with the modified elements.
Simple example:
const numbers = [1, 2, 3, 14]; const doubleNumbers = numbers.map( function multiplyNumber(number) { return number * 2; } ); console.log(doubleNumbers) // Outputs [2, 4, 6, 28]In this example, the method will run a loop over
numbers. On each iteration, the method will callmultiplyNumberand store the return value in another array. Once the loop is over, it will return the new array.4
u/callmelucky May 30 '21
Adding to this, there's a couple of ways you could make this (arguably) more readable.
1. Define the argument function externally:
function multiplyNumber(number) { return number * 2; } const doubleNumbers = numbers.map(multiplyNumber)note: I think
doubleNumberormultiplyByTwowould be better names for that function.2. Use an anonymous arrow function as the argument (my preference):
numbers.map(n => n*2)3
u/HalfVirtual Oct 08 '21
Why do you set (number) when the variable name is “numbers”? Is it because it’s an array or numbers?
1
u/adzrifsidek Apr 09 '24
I think (number) represents each individual element in array. While numbers represent the entire array
2
u/MintCity Apr 15 '22
320 days late, but same question about the distinction between numbeR and numbeRS
2
u/LakeInTheSky May 30 '21
I didn't know about fill, but looking at the docs from MDN you need to flip the arguments, value is always first.
Also, it applies the changes to the original array.
2
May 30 '21
The original that this is based on is more informative and correct... It's like someone took their post and actively tried to make it worse
1
u/192_168_1_x May 30 '21
Oh, nice find! Unfortunately, .fill is still wrong in the original, the parameters are flipped - but agree on whole that one is better.
112
u/GPT-4-Bot May 29 '21
When you've gotten comfortable with map, filter, and reduce your code becomes so much cleaner
24
u/Budget_Instruction49 May 29 '21
what else to learn to be more cleaner
40
u/GPT-4-Bot May 29 '21
Structuring and breaking out your code, your main init function should read like a story and all the ugly stuff is split out into functions
7
u/Budget_Instruction49 May 29 '21
main init fuction ? do you mean app.js (i am noobie)
22
u/SoBoredAtWork May 29 '21
Just in general. Code should be readable - almost like a story. Let's pretend the "init" is renderPage()...
function renderPage() {
renderUserList();
renderBlogPosts();
}
function renderUserList() {
const users = await getUsers();
buildUserList(users);
}
function buildUserList() {
// do stuff
}
function renderBlogPosts() {
const blogPosts = await getBlogPosts();
buildBlogPostList(blogPosts);
}6
u/WhiteKnightC May 29 '21
In my work we use a Pub/Sub system so it cannot be as clean but a good 'trick' for me is making standard naming for handling things:
getX() -> handleXSuccess() and handleXError()
2
u/_Invictuz May 29 '21
Is the init function for a specific design pattern or are we just talking about OOP?
13
u/Macaframa May 29 '21
Init is short for initializing. Every piece of code has to be run somewhere. Op is saying init as the place where your code starts running. It can be named anything. But what their saying is that one function is run, then that runs other functions in succession that are all named to “tell a story” init()
function init() { getUsers(); setUserAbilities(); setUpInitialState(); startWatchers(); notifyTracking(); }21
u/SoBoredAtWork May 29 '21
Arrow functions. Destructuring. Default function parameters. Optional chaining. Async/await.
...a few that immediately come to mind.
7
u/Parkreiner May 29 '21
Arrow functions do make code more concise, but, especially if you're using a higher-order function and creating a function expression inside the call, a named function will probably be more clear.
I think anonymous functions are fine if you're doing something simple like getting an object property, but the moment they become even a little bit more involved, giving the function a name helps make the code more clear – both to other people and to yourself down the line.
4
u/SoBoredAtWork May 30 '21 edited May 30 '21
Arrow functions are great for things like...
const maleUsers = users.filter(user => user.gender === "Male")3
u/addiktion May 30 '21
Agreed. I’d just say one thing with this and that is to avoid using “x” and instead use “user” just so its clear what we are talking about in the filter. This also has the advantage of thinking about each iteration as a singular thing you are working with and what you are testing for in that context.
1
u/SoBoredAtWork May 30 '21
I originally had it that way and switched it for brevity. But you're right... readability is always > brevity. I changed it.
4
u/fonzane May 29 '21
Getting comfortable with typescript (if you haven't already) and typing out as much as possible heavily improves code structure and coding experience in my pov. :)
1
u/Budget_Instruction49 May 29 '21
i am learning react now. should i move to angular ?
4
u/fonzane May 30 '21
I think that depends on what your goals are. From what I've heard react is more popular and more asked for in the industry. I personally came to love angular and I think I've heard that becoming good at angular helps you become a better dev in general. Maybe someone with good knowledge in both frameworks (I think maximillian schwarzmüller has a good comparison video about it and about what to learn) can help clarify your view better :).
3
1
u/BrohanGutenburg Apr 17 '24
I learned js when I stumbled into developing for Salesforce. The one upside was it taught me to split my code up early into controllers, helpers, renderers, etc.
1
u/code_matter May 29 '21
I would look into Lodash! Pretty much the same function, but like on steroids. Look it up :)
3
15
u/rauschma May 29 '21
Two small issues:
Order of arguments:
.fill(value, start)The method names are
.findIndex()and.indexOf().
8
u/Fun_Kangaroo512 May 29 '21
What about reduce
4
u/ssjskipp May 29 '21
Doesn't have a clean "shape" representation like these do. Reduce is kind of like the low-level version of all of these
2
u/nighthawk648 May 29 '21
You should include .flat!!! I was facing an issue for weeks that .flat solved. I felt like an absolute nimrod.
1
u/192_168_1_x May 29 '21
.flat would be good, .reduce is the only “glaring omission” IMO though. So many use cases for that method (one of which is flattening an array! 😎)
2
u/nighthawk648 May 29 '21
Maybe I should look up this .reduce function
3
u/192_168_1_x May 29 '21
for sure
.reduce MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
And .flat MDN coincidentally has a guide on how to use reduce to achieve the same thing- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
//apologies for formatting, on mobile right now
1
u/callmelucky May 30 '21
Wait, are you saying IE doesn't support
.reduce()? Wtf??In any case, flattening nested arrays is a great task for practising recursion:
function flatten(el) { if (!Array.isArray(el)) { return el } else { if (el.length() > 1) { const first = el[0] const remaining = el.slice(1, el.length()) return [flatten(first)].concat(flatten(remaining)) } else { return el } } }Something like that anyway, did this on my phone and have not tested ;)
1
u/192_168_1_x May 30 '21
I wasn’t saying that, but whoever said that I think meant IE doesn’t support .flat because it’s a relatively new method
1
u/callmelucky May 30 '21 edited May 30 '21
Oh, you meant it's a glaring omission from your OP, I see. Eh, I wouldn't beat yourself up about it (I assume you're not haha),
.reduce()is markedly more complex than the others there - ironically, it's hard to reduce that method that much ;)3
u/Parkreiner May 29 '21
I think that might be part of the reason why it's not included. It's so versatile that it's hard to capture everything it can do in a simple picture.
2
May 29 '21
For those of you who still need to have IE compatible builds, .flat won't work FYI.
I know I know IE bad, wish our clients agreed.
10
3
3
u/Noones_Perspective May 30 '21
This is so useful and such a good way to teach those new to the language. I would love to see more examples of this and other methods!
5
2
u/rauschma May 29 '21
Nice! I’d add square brackets to make the distinction between values and arrays of values clearer. Then you see immediately that .find() returns a value and not an array.
2
2
u/S7venE11even May 29 '21
can u explain the fill one? i didn't get it.
5
u/LakeInTheSky May 30 '21
The example from the illustration has an error in the argument order, it should be like this:
⬛⬛⬛⬛.fill(⚫, 1) --> ⬛⚫⚫⚫
It "fills" a section of the array with a specific value, replacing the previous values. It modifies the original array.
The first argument is the value you'll use to fill the array. The second argument is the start index (i.e. it will start filling at this index). It also has a third argument, the end index. If you don't specify that argument, it will fill until the end of the array.
In the example from the illustration, it will fill the array with circles starting from index 1 until the end.
2
u/Groundbreaking92 May 29 '21
I just needed this info. I don’t know if it is random luck or fate but thank you haha
2
2
u/nickdrake47 May 30 '21
Is it a good idea to use Lodash in entire React project, instead of ES6 syntax array methods?
2
1
1
1
1
u/Noones_Perspective May 30 '21
.findIdexOf —— is that an actual method or has the author mixed the .findIndex and .indexOf together by accident?
1
1
u/daneelr_olivaw May 29 '21
Why doesn't .fill work from 0, if findIndexOf works that way? Annoying inconsistence.
14
u/delventhalz May 29 '21
6
u/daneelr_olivaw May 29 '21
So not only is this chart not helpful but also just plain wrong.
4
u/delventhalz May 29 '21
I think the visual metaphor is useful. That said,
findIndexandfillare both pretty niche, and have typos, so I would probably just cut those.1
u/MeMakinMoves May 29 '21
Funnily enough I just learnt about findindexof an hour ago while doing my todo list project, learning about niche stuff helps a lot when you run into situations where u need it
5
0
0
May 29 '21
[deleted]
2
u/illepic May 29 '21
A legit game-changer for those of us that had to do this in less elegant ways in ES5.
1
u/callmelucky May 30 '21
Python has equivalent builtins,
all()andany(). It's the kind of thing that I think most people don't have a use case for every day, but it's great to whip them out when the opportunity. Very intuitive to understand.
40
u/192_168_1_x May 29 '21
I think this serves as a great reference, especially for visual learners. I found this in a dev group I joined on LinkedIn, but author source is unknown.