Skip to content

Instantly share code, notes, and snippets.

@luvuong-le
Last active July 6, 2020 13:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luvuong-le/99de066dca6cc37d44826ef58c8e767a to your computer and use it in GitHub Desktop.
Save luvuong-le/99de066dca6cc37d44826ef58c8e767a to your computer and use it in GitHub Desktop.
/**
* -------------------------------------------------------------
* 1. Removing Duplicates from an array
* -------------------------------------------------------------
* @description We make use of sets and create an array from a Set. Sets don't allow duplicates
* @returns [1,2,3,1,2,3] -> [1,2,3]
*/
const duplicates = [1, 2, 3, 1, 2, 3];
const removedDuplicates = Array.from(new Set(duplicates));
const removedDuplicatesSpread = [...new Set(duplicates)];
/**
* -------------------------------------------------------------
* 2. Empty an array
* -------------------------------------------------------------
* @description Set length of array = 0
* @returns ["a","b","c"] -> []
*/
const arrayToEmpty = ["a", "b", "c"];
arrayToEmpty.length = 0;
/**
* -------------------------------------------------------------
* 3. Map an array without using array.map
* -------------------------------------------------------------
* @description We can use Array.from() to accomplish this
* @returns [1,2,3,4,5] -> [2,4,6,8,10]
* @returns ['John Doe', 'Karen Smith', 'Joey Brown']
*/
const nums = [1, 2, 3, 4, 5];
const mappedArray = Array.from(nums, num => num * 2);
const people = [
{
firstName: "John",
lastName: "Doe"
},
{
firstName: "Karen",
lastName: "Smith"
},
{
firstName: "Joey",
lastName: "Brown"
}
];
const names = Array.from(people, person => `${person.firstName} ${person.lastName}`);
/**
* -------------------------------------------------------------
* 4. Reversing an array
* -------------------------------------------------------------
* @description Built in method using .reverse()
* @returns [4,3,2,1] -> [1,2,3,4]
*/
const arrayToReverse = [4, 3, 2, 1];
console.log(arrayToReverse.reverse());
/**
* -------------------------------------------------------------
* 5. Filling an array with .fill() and .map()
* -------------------------------------------------------------
* @description We can use Array.fill() and then .map()
* @returns array of 10 random different numbers
*/
// This has no random instance or difference
const randomNumbers = new Array(10).fill(getRandomNumberBetween(10));
console.log(randomNumbers);
const randomNumbers2 = new Array(10).fill().map(_ => getRandomNumberBetween(10));
console.log(randomNumbers2);
// Get random number between function
function getRandomNumberBetween(num) {
return Math.floor(Math.random() * num + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment