Skip to content

Instantly share code, notes, and snippets.

@0xAliRaza
Last active March 8, 2022 13:48
Show Gist options
  • Save 0xAliRaza/8ea9cc06226cae90609fa1cdcf93fcca to your computer and use it in GitHub Desktop.
Save 0xAliRaza/8ea9cc06226cae90609fa1cdcf93fcca to your computer and use it in GitHub Desktop.
Demonstration of some common js array methods.
/* 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