Skip to content

Instantly share code, notes, and snippets.

View dalkegama's full-sized avatar
๐Ÿค–

Dhanik Alkegama dalkegama

๐Ÿค–
View GitHub Profile
const arrayOneLevelDeep = [6,9,[6],6];
[].concat(...arrayOneLevelDeep);
// or
[].concat.apply([],arrayOneLevelDeep);
// Returns
[6, 9, 6, 6]
const someArray = [1, 2, , , [3, 4, [5, null, ["", 8, [undefined, 10]]]]];
someArray.flat(Infinity).filter(Boolean).map(Number);
// or
someArray.toString().split(",").filter(Boolean).map(Number);
// Both returns
[1, 2, 3, 4, 5, 8, 10]
const someArray = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
// toString()
someArray.toString().split(",").map(Number);
// or you could use template literal which is faster than toString()
`${someArray}`.split(",").map(Number);
// Returns
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const arrayWithEmptySlots = [1, 2, , 3, , 4].flat();
//Returns
[1, 2, 3, 4]
const someArray = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
someArray.flat(Infinity);
// Returns
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@dalkegama
dalkegama / js-array-flat.js
Last active December 6, 2020 18:48
example of array.flat() with a depth of 1
const monkeys =["๐Ÿ™ˆ",["๐Ÿ™‰","๐Ÿ™Š"],"๐Ÿ’"].flat();
// one above is same as the one below
const monkeys = ["๐Ÿ™ˆ",["๐Ÿ™‰","๐Ÿ™Š"],"๐Ÿ’"].flat(1);
// Returns
[๐Ÿ™ˆ,๐Ÿ™‰,๐Ÿ™Š,๐Ÿ’]
// Long way
if(array.indexOf(item) > -1) // Item found
if(array.indexOf(item) === -1) // Item NOT found
// Shorthand way ๐Ÿ‘๐Ÿฝ
if(array.includes(item))// Item found
if(!array.includes(item))// Item NOT found
if(~arr.indexOf(item)) // Item found
let someString = "doubt-not";
someString = "false";
!!someString // returns true
someString = "0";
!!someString //returns true
let someString = undefined;
!!someString //returns false
// Use this:
Boolean(someString); // returns true, same as !!someString
Boolean("0"); //returns true, in JavaScript, a non-empty string is always true.
//Not this:
const foo = new Boolean(bar); // returns a wrapper object
Number(someStringNum) + 2; // returns 5.5
Number(null); // returns 0
Number(""); // return NaN
// Fast but messy
someStringNum * 1 + 2; // returns 5.5