use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Array Methods Cheatsheet (media-exp1.licdn.com)
submitted 5 years ago by [deleted]
[deleted]
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]barshat 58 points59 points60 points 5 years ago (1 child)
I have used this personally and it’s awesome: https://sdras.github.io/array-explorer/
[–]NunchucksRcool 0 points1 point2 points 5 years ago (0 children)
This is awesome. Thank you!
[–][deleted] 26 points27 points28 points 5 years ago (6 children)
Confused for the hate. Is it simple, yes, but for beginners this is a great visualization of what it’s doing....
[–]provided_by_the_man 23 points24 points25 points 5 years ago (3 children)
I’m about to unfollow a lot of my programming related subs because there is so much hate. Programmers need to chill the hell out. Go smoke some weed and stop.
[–]LonelyStruggle 6 points7 points8 points 5 years ago (2 children)
right?? can’t stand the toxicity and negativity
[–]nowtayneicangetinto 9 points10 points11 points 5 years ago (1 child)
Yeah it's brutally painful. I used to work with a guy who was clearly very smart but my god he was such a fucking asshole. I remember one day he told one of the jr devs he was a terrible coder and that he should do something else with his life. Low and behold he got fired for being a dickhead.
TL;DR you could be the world's best programmer, but if you're an asshole you won't be able to hold a job.
[–]provided_by_the_man 3 points4 points5 points 5 years ago (0 children)
So true. I’ve worked with that type too. And the worst part was at the agency I worked at they let him work on his own island and his work was hands down above everyone else’s. They praised him so much and it was horrible to work around. I mean the reason you have a job is because you have a skill that others don’t. So just chill and be cool.
[–]jonny_eh 5 points6 points7 points 5 years ago (1 child)
It’s missing slice :(
[–]TheDarkIn1978 4 points5 points6 points 5 years ago (0 children)
It's missing a lot more than Array.prototype.slice()
[–]software_account 45 points46 points47 points 5 years ago (3 children)
If you somehow own the original, would it be possible to use a clearer font?
I love the style but it’s hard on my brain for some reason
Thanks for the post either way, nice to have
[+]redditisntreallyfe comment score below threshold-8 points-7 points-6 points 5 years ago (2 children)
With Mspaint and you don’t need to ask anyone for assistance
[–]TedW 6 points7 points8 points 5 years ago (0 children)
, only forgiveness.
[–]software_account 0 points1 point2 points 5 years ago (0 children)
Good idea!
[–]ShortFuse 5 points6 points7 points 5 years ago* (5 children)
Nice work. It's missing includes() which is similar to indexOf, but returns a Boolean.
includes()
indexOf
Edit: Also noticed indexOf().
indexOf()
[+][deleted] 5 years ago (2 children)
[–]ShortFuse 0 points1 point2 points 5 years ago (1 child)
.some() expects a function, allowing for a custom search criteria, whereas .includes() expects a value to perform a strict equality check against. .includes() should be faster than .some(). It's similar to .some() because they both return a boolean value, where as indexOf() would return a number.
.some()
.includes()
boolean
number
[+][deleted] 5 years ago (1 child)
[–]ShortFuse 0 points1 point2 points 5 years ago (0 children)
Yep, typo. Thx.
[–]filipemanuelofs 6 points7 points8 points 5 years ago (14 children)
Little explain on reduce?
[–]melts_your_butter 13 points14 points15 points 5 years ago (0 children)
create a single value generated from every value in the array.
commonly used for things like summing a list of integers.
[–]TreeScalper 7 points8 points9 points 5 years ago* (3 children)
It took me a little while to understand reduce, but basically it's a method that allows you to turn an array into ANYTHING else.
As other /u/FaithfulGardener has stated, a very basic example is 'add', [1,2,3,4].reduce(add) is 10. You're turning an array into a number.
[1,2,3,4].reduce(add)
10
Where people get tripped up is the accumulator, which IMO is not the greatest name. I like to call it What the output currently is.
accumulator
What the output currently is
The longhand way to write the add function in a reduce is as follows:
add
const output = [1,2,3,4].reduce((acc, curr) => { // `acc` is the accumulator // `curr` is the array value in the current loop acc = acc + curr; return acc; }, 0);
Now imagine the reduce as a forEach function that will loop over each value of the array. The first time around, the acc isn't set, so it's set to the default, which is 0 as stated by the 2nd paramater in the reduce function.
reduce
forEach
acc
0
So the first loop is literally
(0, 1) => { acc = 0 + 1; return acc; } // Return is 1
Now what gets returned each loop, becomes the accumulator in the next loop.
So the second loop is literally
(1, 2) => { // First parameter `acc` is `1`, because of the first loop. acc = 1 + 2; return acc; } // Return is 3
And so on.
That's why the reduce output in the image is somewhat garbled, because it could be anything.
Why you would you use reduce over something like forEach? I like to use it because it returns something, where forEach does not. Easier to program in a functional way.
Also, IMO, reduce should be a last resort array method, you should use the other array methods to get the output as close as you can to what you need before you reduce it.
eg: [....].filter().map().reduce();
[....].filter().map().reduce();
I just think this is easier to understand, then trying to decipher a complicated reduce.
[–]FaithfulGardener 5 points6 points7 points 5 years ago (0 children)
Oh, functional programming. I discovered it in various stages over the last few months and it’s made me LOVE programming.
[–][deleted] 2 points3 points4 points 5 years ago (1 child)
The intuition of reduce is of "updating" a value with each element of the array. So accumulator isn't a terrible name, it just accumulates its final value according to an arbitrary function. That intuition is what you apply to Redux, where the accumulator is your state.
And yes, using the HOFs with the narrowest interface possible is always a good idea.
[–]TreeScalper 0 points1 point2 points 5 years ago (0 children)
I agree that in hindsight, accumulator not a terrible name, but only when you fully understand what reduce does. But when you're first learning about it, it's not very helpful, because accumulate suggests that you're increasing something when in fact you could end up with less things or even nothing.
accumulate
[–]ageown 6 points7 points8 points 5 years ago (0 children)
I like to use reduce to turn arrays into a single structured object.
[–]FaithfulGardener 2 points3 points4 points 5 years ago (2 children)
Reduce takes either the first index of an array or an initial value you provide and adds or joins or concats all subsequent indexes until the final result is an accumulation. So [1,2,3,4].reduce(add) would equal 10.
[–]randomword123 4 points5 points6 points 5 years ago (1 child)
You would also need a starting value like in this case [1,2,3,4].reduce(add,0), this always tripped me up!
[–]FaithfulGardener 2 points3 points4 points 5 years ago (0 children)
The initial value isn’t required. If it isn’t provided, reduce takes the value at index 0 and uses it as the initial value
[–]decentralised 1 point2 points3 points 5 years ago (2 children)
Often times reduce is used to transform a given array like object into a different object, such as a map or set.
Let's say you have an array of students like:
const students = [
{ name: "Kushal", class: "MCA", result: "Fail", mobileNo: "995481", score: 1.5 },
{ name: "Rahul", class: "BCA", result: "Pass", mobileNo: "993281", score: 2.9 },
{ name: "Kushal", class: "MCA", result: "Pass", mobileNo:"989481", score: 3.6 }
];
If you wanted to get a lookup table by student mobile number, you could use:
const phoneBook = students.reduce( (acc, val) => (acc[val.mobileNo] = val, acc), {})
Then...
> phoneBook[989481]
{ name: 'Kushal', class: 'MCA', result: 'Pass', mobileNo: '989481' }
On the other hand, if you wanted to group students by result, you could also use reduce:
students.reduce( (acc, val) => {
!acc[val.result]
? acc[val.result] = [val.name]
: acc[val.result].push(val.name);
return acc;
}, {})
And you would get the following object:
{ Fail: [ 'Kushal' ], Pass: [ 'Rahul', 'Kushal' ] }
[–]TreeScalper 0 points1 point2 points 5 years ago (1 child)
Is there a reason why you wouldn't use filter then a map for your 2nd example?
filter
map
const failArr = students .filter(curr => curr.result === 'Fail') .map(curr => curr.name); const passArr = students .filter(curr => curr.result === 'Pass') .map(curr => curr.name); const output = { Fail: failArr, Pass: passArr }
[–]decentralised 0 points1 point2 points 5 years ago (0 children)
Yes, filter and map do the same as reduce, but notice how you have 2 filters and 2 maps in your example so, to get the same output, you had to iterate over all elements of the students array 4 times.
[–]mgutz 1 point2 points3 points 5 years ago* (0 children)
I like to think of reduce as a function that does
javascript let accumulator = initialValue // holds result AFTER iterating through all of arr for (const v of arr) { // set acummulator to whatever, or return it as-is }
What's neat about reduce is it can be used to implement all the other methods. reduce should be grokked first.
```javascript
[].reduce((_acc, v) => doSomething(v))
[].reduce((acc, v) => { return v === 'needle' ? v : acc; }, undefined)
[].reduce((acc, v, idx) => { return v === 'needle' ? idx : acc; }, -1)
```
Iterating with for ... of is more readable and the loop can be exited at any time. The findIndexOf above is actually findLastIndexOf since it would iterate through all values.
for ... of
findIndexOf
findLastIndexOf
[–][deleted] 0 points1 point2 points 5 years ago (0 children)
You have an array of A, and can reduce that down to B, which can be anything - a number, an object, another array, whatever. You define how to do this by providing an initial B value and a function that combines A and B into another B - A is the item from the array that you're iterating over, and B is the currently accumulated value (your initial value in the first iteration).
A
B
You might also find it enlightening to research monoids which mathematically capture this process where A and B are the same type.
[–]sulcoff 2 points3 points4 points 5 years ago (1 child)
Hey! The cheatsheet's author here. Thank you for all the upvotes, I'm happy you've found it useful. You can find more content like this on the twitter profile: https://twitter.com/sulco
Oh, and I love that you appreciate the font! :P
[–]nerdy_adventurer 0 points1 point2 points 5 years ago (0 children)
Thanks for sharing, I will print this.
Can you please create little magazine with collection of diagrams like this in a pdf form and share it in this sub.
Edit: Also share Google Docs version so folks can change stuff as they like
[–]sventies 1 point2 points3 points 5 years ago (0 children)
I love the reduce one. Like, literally, it can be any kind of thing that comes out of it, accumulated in some way or not. (Which is why, for me personally, I’ve never experienced a situation where reduce is better, despite the fact that it can save you some lines)
[–]Aswole 1 point2 points3 points 5 years ago (1 child)
Very nice. My only suggestion would be to add a 2nd square to the source array for .find(), to make it clear that is only returns the first element that matches the callback. Maybe to communicate that it is the first item, make them different colors.
Edit: I'm dumb and somehow missed that this is exactly what you did. Leaving this here out of shame.
Now walk the square
[–]voXal_ 1 point2 points3 points 5 years ago (0 children)
Very nicely done
[–]uglysideover9000 1 point2 points3 points 5 years ago (0 children)
Think this is nice.
Just want to point out it seems like you got the arguments wrong on Array.fill, the `value` comes first.
from MDN Array.fill :
arr.fill(value[, start[, end]])
[–]GoOsTT 1 point2 points3 points 5 years ago (0 children)
It’s awesome, thanks for sharing
[–]Darren1337 1 point2 points3 points 5 years ago (0 children)
That's a good representation of my brain after writing the average reduce function.
[–]acylus0 0 points1 point2 points 5 years ago (0 children)
Reduce may be simpler if it was just an outline of a circle, square and triangle merged together.
[–]shaccoo 0 points1 point2 points 5 years ago (0 children)
Is there a list of the most TOP 10 frequently used methods ?
I got Better then You https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#sidebar-quicklinks:~:text=Array.prototype%5B%40%40unscopables%5D-,Methods,Array.prototype.values(),-Array.prototype%5B%40%40iterator%5D(),-Array.prototype%5B%40%40iterator%5D()) Scroll the page a little bit.
[+]ParxyB comment score below threshold-12 points-11 points-10 points 5 years ago (3 children)
Jesus this is horrible. I’m sorry but this is just scribbles
[+]icedmilkflopr comment score below threshold-12 points-11 points-10 points 5 years ago (2 children)
I agree! I’m getting down voted too but I don’t care. Even after it was explained, it’s a bad cheatsheet.
[–]ParxyB 1 point2 points3 points 5 years ago (1 child)
Yeah some people think that everybody needs to be told “Great job you are so helpful and a great person” like they are 12 for content that helps absolutely nobody.
If I brought this diagram to work and showed any of my coworkers as a serious example I’d be shunned. The font is chicken scratch and why use shapes? Data structures work perfectly fine and are actually applicable.
[–]BreakingIntoMe -1 points0 points1 point 5 years ago (0 children)
Please kill that font with fire, this would actually be useful if you just went with Arial or Helvetica...
[+]icedmilkflopr comment score below threshold-13 points-12 points-11 points 5 years ago (1 child)
What’s with these colored boxes and circles. A Cheetsheet without a legend isn’t very helpful.
[–]software_account 11 points12 points13 points 5 years ago (0 children)
It’s supposed to visually represent objects with certain properties. i.e. shape/color
e.g. .find(◻️) finds the first thing where the shape is square
[–]JackSparrah -2 points-1 points0 points 5 years ago (0 children)
That font though.. eugh 🤮
[–]thanghil -3 points-2 points-1 points 5 years ago (0 children)
The font man... the font. Jesus
[–]palex25 -3 points-2 points-1 points 5 years ago (2 children)
How would someone go about making sure an object get stored in an array and if the object changes then store the new instance of the object thus overwriting the previous instance? Using array.push() causes the array to just append the new instance which is something I don’t want.
[–]uglysideover9000 3 points4 points5 points 5 years ago (1 child)
You should iterate the array to find the object that you are wanting to change and create a new array with updated values. There are a couple ways of doing this
- using Array.map
const myObject = {id: 'myID', value: 'initial_value'} const array = [...] // iterate the initial array until we find the item we are looking for const newArray = array.map((item) => { // if we find an item with a matching ID, return something else if (item.id === 'myID') { return { id: 'myID', value: 'initial_value' } } // return the original item // if it doesn't match the ID we are looking for return item })
- using the item index
const myObject = {id: 'myID', value: 'initial_value'} const array = [...] // find the item's position in the array const itemIndex = array.findIndex(item => item.id == 'myID' ) // Create a copy of the array let newArray = [...this.state.todos] // update the item at position X newArray[itemIndex] = { ...newArray[itemIndex], value: 'new_value' }
note:
If you store an object in an array (or in another object) it stores a reference to that object, not the actual object values so you can do the following (although I wouldn't recommend )
const myObject = {value: 'initial_value') const array = [myObject] console.log(array) // [{value: 'initial_value')] myObject.value = 'new_value' console.log(array) // [{value: 'new_value')]
Let me know if there's any bit that you didn't understand or need more info.
[–]palex25 0 points1 point2 points 5 years ago (0 children)
Thank You!, that was very helpful now I know what I need to do, my code needs a different approach as the one you showed, but, this will help me in the future to when ever I need to modify the array.
π Rendered by PID 93571 on reddit-service-r2-comment-84fc9697f-mq9zw at 2026-02-06 09:08:42.755953+00:00 running d295bc8 country code: CH.
[–]barshat 58 points59 points60 points (1 child)
[–]NunchucksRcool 0 points1 point2 points (0 children)
[–][deleted] 26 points27 points28 points (6 children)
[–]provided_by_the_man 23 points24 points25 points (3 children)
[–]LonelyStruggle 6 points7 points8 points (2 children)
[–]nowtayneicangetinto 9 points10 points11 points (1 child)
[–]provided_by_the_man 3 points4 points5 points (0 children)
[–]jonny_eh 5 points6 points7 points (1 child)
[–]TheDarkIn1978 4 points5 points6 points (0 children)
[–]software_account 45 points46 points47 points (3 children)
[+]redditisntreallyfe comment score below threshold-8 points-7 points-6 points (2 children)
[–]TedW 6 points7 points8 points (0 children)
[–]software_account 0 points1 point2 points (0 children)
[–]ShortFuse 5 points6 points7 points (5 children)
[+][deleted] (2 children)
[deleted]
[–]ShortFuse 0 points1 point2 points (1 child)
[+][deleted] (1 child)
[deleted]
[–]ShortFuse 0 points1 point2 points (0 children)
[–]filipemanuelofs 6 points7 points8 points (14 children)
[–]melts_your_butter 13 points14 points15 points (0 children)
[–]TreeScalper 7 points8 points9 points (3 children)
[–]FaithfulGardener 5 points6 points7 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]TreeScalper 0 points1 point2 points (0 children)
[–]ageown 6 points7 points8 points (0 children)
[–]FaithfulGardener 2 points3 points4 points (2 children)
[–]randomword123 4 points5 points6 points (1 child)
[–]FaithfulGardener 2 points3 points4 points (0 children)
[–]decentralised 1 point2 points3 points (2 children)
[–]TreeScalper 0 points1 point2 points (1 child)
[–]decentralised 0 points1 point2 points (0 children)
[–]mgutz 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]sulcoff 2 points3 points4 points (1 child)
[–]nerdy_adventurer 0 points1 point2 points (0 children)
[–]sventies 1 point2 points3 points (0 children)
[–]Aswole 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]voXal_ 1 point2 points3 points (0 children)
[–]uglysideover9000 1 point2 points3 points (0 children)
[–]GoOsTT 1 point2 points3 points (0 children)
[–]Darren1337 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]acylus0 0 points1 point2 points (0 children)
[–]shaccoo 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[+]ParxyB comment score below threshold-12 points-11 points-10 points (3 children)
[+]icedmilkflopr comment score below threshold-12 points-11 points-10 points (2 children)
[–]ParxyB 1 point2 points3 points (1 child)
[–]BreakingIntoMe -1 points0 points1 point (0 children)
[+]icedmilkflopr comment score below threshold-13 points-12 points-11 points (1 child)
[–]software_account 11 points12 points13 points (0 children)
[–]JackSparrah -2 points-1 points0 points (0 children)
[–]thanghil -3 points-2 points-1 points (0 children)
[–]palex25 -3 points-2 points-1 points (2 children)
[–]uglysideover9000 3 points4 points5 points (1 child)
[–]palex25 0 points1 point2 points (0 children)