logo

JavaScript Cheatsheet

Array

Insert:

// insert, front
arr.unshift();

// insert, back
arr.push();

// delete from back
arr.pop();

// delete from front
arr.shift();

// Delete without changing indices of other elements(leaving a hole)
delete arr[i];

// Delete and shift other elements forward (modifying array in place)
var index = arr.indexOf(5);
if (index > -1) {
  arr.splice(index, 1);
}

// Delete by filtering
keys.filter((key) => key != 'foo');

// subarray
arr.slice(0, 10); // first 10 items
arr.slice(start, end);

// clone
const clone = arr.slice(0);

// check element in array
arr.includes(element);

// map
[1, 2, 3].map((x) => x * 2);

// array length
[1, 2, 3].length;

// index of
[2, 5, 9].indexOf(5);

// join 2 arrays
[1].concat([2])[(1, 2)];

// split
const [a, b, c] = str.split('-');

// zip
const a = [1, 2, 3]
const b = ['A', 'B', 'C']
a.map((v, i) => [v, b[i]])
// [[1, 'A'], [2, 'B'], [3, 'C']]

// max / min
a = [1,23,57,4]
Math.max(...a)

// sort
arr.sort((a,b) => { return parseFloat(a.data) - parseFloat(b.data) } );

arr.sort((a,b) => { return a.str.localeCompare(b.str) } );

arr.sort((a,b) => { return a.str.toUpperCase().localeCompare(b.str.toUpperCase() } );

Map (Object)

// create
const a = {};

// set value
a['key'] = 'value';

// get value
a['key'];

// get or else:
//   if 'key' is not in the object, return 0
a['key'] || 0;

// clone
let clone = Object.assign({}, obj);

// get keys, values, entries
Object.keys(obj);
Object.values(obj);
Object.entries(obj);

// loop keys, entries
for (const key in object) {
  console.log(`${key}: ${object[key]}`);
}

for (const [key, value] of Object.entries(obj)) {
  // ...
}

// contains key
'key' in obj;

obj.hasOwnProperty('key');

// container value
Object.values(obj).includes('foo');

// destructuring
const { children, location } = this.props;

// spread
var a = 1,
  b = 2,
  c = 3;
var x = { x: 4, y: 5, z: 6 };

var obj = { a, b, c, ...x };

console.log(obj); //{a: 1, b: 2, c: 3, x: 4, y: 5, z: 6};

// sort object
const sortedObj = Object.keys(obj)
  .sort()
  .reverse()
  .reduce((newObj, k) => {
    newObj[k] = obj[k];
    return newObj;
  }, {});

Set

const fooSet = new Set();

fooSet.add(1);
fooSet.delete(1);
fooSet.has(1);

// convert from array
const arr = [1, 2, 3];
const set = new Set(arr);