Last active
March 8, 2022 13:48
-
-
Save 0xAliRaza/8ea9cc06226cae90609fa1cdcf93fcca to your computer and use it in GitHub Desktop.
Demonstration of some common js array methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* JavaScript Array Methods */ | |
let emojis; | |
function resetEmojis() { | |
emojis = ["one", "two", "three", "four"]; | |
} | |
// Instantiate emojis array | |
resetEmojis(); | |
/** | |
* | |
* @param {Function} fn - A callback function to execute | |
*/ | |
function execAndLog(fn, fnName) { | |
console.log("Emoji array before ▶ ", emojis); | |
console.log(`${fnName} ▶ `, fn()); | |
console.log("Emojis array after ▶ ", emojis, "\n\n"); | |
} | |
/** Below methods doesn't modify the original array */ | |
// Concatenate two or more arrays | |
execAndLog(() => emojis.concat([1, 2]), "emojis.concat([1, 2])"); | |
// Convert an array to a string | |
execAndLog(() => emojis.join("-"), "emojis.join('-')"); | |
// Get shallow copy of a portion of an array | |
execAndLog(() => emojis.slice(0, 2), "emojis.slice(0, 2)"); | |
// Get index of an array element | |
execAndLog(() => emojis.indexOf("three"), "emojis.findIndex('three')"); | |
// Check if an element exists in an array | |
execAndLog(() => emojis.includes("none"), "emojis.includes('none')"); | |
// Find a specific element in an array | |
execAndLog(() => emojis.find((el) => typeof el === "string"), "emojis.find(/* El of type string */)"); | |
// Find index of a specific element in an array | |
execAndLog(() => emojis.findIndex((el) => typeof el === "string"), "emojis.find(/* Index of el of type string */)"); | |
// Create a new and modified array | |
execAndLog(() => emojis.map((el) => el + 'test'), "emojis.map(/* Add 'test' to all elements */)") | |
/** There are more but I couldn't add them because another problem set was given */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment