Skip to content

Instantly share code, notes, and snippets.

@greybax
Last active December 10, 2020 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greybax/74edda54d23f11787c69caf255dfbd39 to your computer and use it in GitHub Desktop.
Save greybax/74edda54d23f11787c69caf255dfbd39 to your computer and use it in GitHub Desktop.

Revert string 'abc' -> 'cba'

str.split('').reverse().join('')

Search substring in string

let a = 'Happy New Year 2019!';
let b = 'Year 2019';
let c = 'Year 2018';

a.indexOf(b) >= 0 ? "Found" : "Not Found";   // return 10 (index of first element of substring in search string); -> "Found"
a.indexOf(c) >= 0 ? "Found" : "Not Found";   // return -1; -> "Not Found"

Change String/Array dynamically (w/o creating new one)

// f.e. we have date in string format:
let date = '20190211';
// but we want it like 2019-02-11

// String -> Array
date = date.split('');

date.splice(4,0,'-');                   // return []; date = ["2", "0", "1", "9", "-", "0", "2", "1", "1"]
date.splice(date.length - 2, 0, '-');   // return []; date = ["2", "0", "1", "9", "-", "0", "2", "-", "1", "1"]

// Array -> String
date = date.join('');                          // return "2019-02-11";

Note: Only arrays have method .splice() and strings are haven't;

Copy arrays by values

newArray = [].concat(array);

Note: this case will works with plain arrays like [1,2,3,4,5] and will not work with arrays contains objects [{a:1},2,3]. Because objects in JS copying by reference and not by value.

Sum elements of array

[1, 2, 3].reduce((a,b) => a + b, 0);

Sum of elements using closure

function sum(a) {
  return function(b) {
    if (b == undefined) 
      return a; 
     else 
      return sum(a+b);   // sum(1)(2)(3)(4)() === 1+2+3+4
  };
}

Get unique values

let array_values = [1, 3, 3, 4, 5, 6, 6, 6, 8, 4, 1];
let unique_values = [...new Set(array_values)];
console.log(unique_values);  // [1,3, 4, 5, 6, 8]

Using length to resize and emptying an array

let arrValues = [1, 2, 3, 4, 5, 6, 7, 8];  
console.log(arrValues.length);  // 8  
arrValues.length = 5;  
console.log(arrValues.length);  // 5  
console.log(arrValues);         // [1, 2, 3, 4, 5]

Min/Max element in array

Min:

[1,2,-3,0,12,9,5].reduce((a,b) => a < b ? a : b);   // return -3;

Max:

[1,2,-3,0,12,9,5].reduce((a,b) => a > b ? a : b);   // return 12;

Decimal to Binary

5..toString(2);   // return "101";

or

Number("5").toString(2);   // return "101";

Type of Object

Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();

Stack

let arr = [1,2];
arr.push(3);      // return 3; arr=[1,2,3]
arr.pop();        // return 3; arr=[1,2]

Queue

let arr = [1,2];
arr.push(3);      // return 3; arr=[1,2,3]
arr.shift();      // return 1; arr=[2,3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment