Skip to content

Instantly share code, notes, and snippets.

@andyj
Last active July 17, 2024 10:09
Show Gist options
  • Save andyj/9626bb130cf8f2fadb84db4913fc2992 to your computer and use it in GitHub Desktop.
Save andyj/9626bb130cf8f2fadb84db4913fc2992 to your computer and use it in GitHub Desktop.
Exploring JS array methods
// This is the code that prompted / created the blog post
// https://www.andyjarrett.com/posts/2024/exploring-array-methods-including-push-pop-shift-unshift-map-filter-reduce-and-others/
// push()
["šŸ„¶","šŸ„¶","šŸ„¶","šŸ„¶"].push('šŸ„µ') // = ["šŸ„¶","šŸ„¶","šŸ„¶","šŸ„¶","šŸ„µ"]
// pop()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].pop() // = ["šŸ˜Ž","šŸ„µ","šŸ„¶"]
// shift()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].shift() // = ["šŸ„µ","šŸ„¶","šŸ¤¢"]
// unshift()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].unshift('šŸ’©') // = ["šŸ’©","šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"]
// map()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].map(item => item + '!') // = ["šŸ˜Ž!","šŸ„µ!","šŸ„¶!","šŸ¤¢!"]
// filter()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].filter(item => item === 'šŸ„¶') // = ["šŸ„¶"]
// reduce()
[1,2,3].reduce((acc, val) => acc + val, 0) // = 6
// some()
[1,2,3].some(val => val > 2) // = true
// every()
[1,2,3].every(val => val > 0) // = true
// find()
[1,2,3].find(val => val > 2) // = 3
// findIndex()
[1,2,3].findIndex(val => val > 2) // = 2
// reverse()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].reverse() // = ["šŸ¤¢","šŸ„¶","šŸ„µ","šŸ˜Ž"]
// at()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].at(1) // = šŸ„µ
// slice()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].slice(1, 2) // = ["šŸ„µ"]
// concat()
["šŸ„¶"].concat(["šŸ„µ"]) // = ["šŸ„¶","šŸ„µ"]
// includes()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].includes('šŸ„µ') // = true
// indexOf()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].indexOf('šŸ„µ') // = 1
// join()
["šŸ˜Ž","šŸ„µ","šŸ„¶","šŸ¤¢"].join(' ') // = "šŸ˜Ž šŸ„µ šŸ„¶ šŸ¤¢"
// flat()
[1,[2,3],[4,5]].flat() // = [1,2,3,4,5]
// flatMap()
[1,2,3].flatMap(val => [val, val * 2]) // = [1,2,2,4,3,6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment