zjunebao
8/15/2019 - 7:18 AM

js ES

Array, Object

/*** Destruct and spread Array, Object */
// Destruct 
const {a,b} = {a:1,b:2}
// Destruct and store in foo,bar
const {a:foo, b:bar} = {a:1,b:2}
// Destruct with default value 0
const {a=0, b=0} = {a:1}

// Destruct array
const [a,b] = [1,2]
// Destruct then swap values
let a=1, b=2
[a,b] = [b,a]
// Destruct with default value
let a,b
([a=1,b=2] = [0])

Map Array to Object

const arr = [{id:1,title:'a'}, {id:2,title:'b'}]
const obj = Object.assign({}, ...arr.map(item => ({[item.id]:item})))
// result: {1:{id:1,title:'a'}, 2:{id:2,title:'b'}}

Transform Object to Array in [[key,value], ...]

const obj = {hello:'world', foo:'bar'}
const arr = Object.entries(obj) 
// result: [['hello','world'], ['foo','bar']]

/* REVERSE */
const obj2 = Object.fromEntries(arr)

Remove Array dupplicates

// "Set"
[...new Set(array)]

// "Filter"
array.filter((item,index) => array.indexOf(item) === index)

// "Reduce"
array.reduce((ac, item) => ac.includes(item) ? ac : [...ac, item], [])

Object isempty

let obj = {}
const isObjectAndIsEmpty = obj && Object.keys(obj).length === 0 && obj.constructor === Object

Array Check Item Exist

// "indexOf"
array.indexOf('foo') !== -1

// "includes"
array.includes('foo')

// "some"
array.some(item => item === 'foo')
array.some(obj => obj.name.toLowerCase() === 'foo')

Array Descructure Skip

const array = ['apple', 'orange', 'banana']
const [,,take] = array // take is 'banana'
const [_,_ignore,take] = array // use _ for useless variable
const [/*apple*/,/*orange*/,take] = array // use of comment
const {length, [length - 1]:last} = array // last is 'banana'

Array

flatMap
// "flatMap" every callback return array will merge into one result array
const fruits = ['apple', 'banana']
fruits.flatMap((name, index) => [name, index])
// ['apple', 1, 'banana', 2]
power
Math.pow(2, 3)
2 ** 3
// 2 pow 3 equal 8
bitwise OR operator
/* remove all after decimal point */
23.9 | 0        // 23
-23.9 | 0       // -23
239 / 10 | 0    // 23
239 / 100 | 0   // 2
time benchmark
console.time('flag')
// do something take time
console.timeEnd('flag')
format JSON
const jsonObject = {foo:'foo', bar:'bar'}

console.log(
  JSON.stringify(jsonObject, null, '\t')
)
every and some
const numbers = [1,2,3,-1]
const isPositive = (n) => (n > 0)

numbers.every(isPositive) // false
numbers.some(isPositive)  // true
cast array
arrayItems.map(Number)   // cast all array items into Number
arrayItems.map(Boolean)  // cast all array items into Boolean