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