1. The Reduce method implements both Map and Filter

Suppose you have an array and you want to update each of its entries (map) and filter some of them (filter). If map and filter are used first, the number group needs to be traversed twice, and reduce is used to simplify writing

const numbers = [10, 20, 30, 40]
const doubledOver50 = numbers.reduce((finalList, num) => {
  num = num * 2
  if (num > 50) finalList.push(num)
  return finalList
}, [])
console.log('doubledOver50', doubledOver50) // [60, 80]
Copy the code

2. The reduce method counts the same number in the array

let cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota']
let carsObj = cars.reduce((obj, name) => {
  obj[name] = obj[name] ? ++obj[name] : 1
  return obj
}, {})
console.log('carsObj', carsObj) // {BMW: 2, Benz: 2, Tesla: 1, Toyota: 1}
Copy the code

3. Use deconstruction tips

// Let param1 = 1; let param2 = 2; [param1, param2] = [param2, param1] console.log('param1', param1) // param1 2 console.log('param2', Param2) // param2 1 // Async function getFullPost () {return await promise.all ([fetch('/post'), Fetch ('/comments')])} const [post, comments] = getFullPost() const [a,...rest] = [...'asdf'] // a: 'a' rest: ['s', 'd', 'f'] // Array shallow copy const arr = [1, 2, 3] const arr = [...arr] // Object shallow copy const obj = {a: 1} const objClone = {... Obj} arr. Slice (0, arr. Length)/array. from(arr) Operator is easy to use Code is also very concise / / array merge const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] const arr = [arr1,... arr2] / [1, 2, 3, 4, 5, Const a = [0, 1, 2, 3, 4, 5] const b = [3, 4, 5, 6, 7, 8] const duplicatedValues = [...new Set(a)].filter(item => b.includes(item)) console.log('duplicatedValues', DuplicatedValues) // duplicatedValues [3, 4, 5] const a = [0, 1, 2, 3, 4, 5] const b = [3, 4, 5, 6, 7 8] const duplicatedValues = [...new Set([...a, ...b])].filter(item => ! a.includes(item) || ! b.includes(item)) console.log('duplicatedValues', duplicatedValues) // duplicatedValues [0, 1, 2, 6, 7, 8]Copy the code

4. Reduce method array flattening

const flatten = (arr, depth = 1) => depth ! = 1? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), []) : arr.reduce((a, v) => a.concat(v), []) console.log(flatten([1, [2], 3, 4])) // [1, 2, 3, 4] console.log(flatten([1, [2, [3, 4, 5, 6], 7, 8], 3)) / / [1, 2, 3, 4, 5, 6, 7, 8] / / can also use the ES6 flat () method for array flattening let arr1 = [[2] 1, 3, 4] let arr2 = [1, [2, [3, [4, 5], 6], 7], 8] console.log(arr1.flat(Infinity)) // [1, 2, 3, 4] console.log(arr2.flat(Infinity)) // [1, 2, 3, 4, 5, 6, 7, 8]Copy the code

5. The reduce method determines the maximum value of the array

const arr = ['s0', 's4', 's1', 's2', 's8', 's3']
const maxS = arr.reduce((prev, cur) => {
const curIndex = Number(cur.replace('s', ''))
  return curIndex > prev ? curIndex : prev
}, 0)
console.log('maxS', maxS) // maxS 8
Copy the code

6. Output an array/object using reduce method

const arr = [1, 2, 3, 4, 5]
const value = arr.reduce((prev, curr) => {
  return curr % 2 === 0 ? [...prev, {value: curr}] : prev
}, [])
Copy the code

7. Object deconstruction of arrays

Arrays can also be object destructed, which makes it easy to get the NTH value of an array

const csvFileLine = '1997,John Doe,US,[email protected],New York';
const {2: country, 4: state} = csvFileLine.split(',')
console.log('country', country) // country US
console.log('state', state) // state New York
Copy the code

8. Generate arrays of [1-100]

new Array(100).fill(0).map((item, index) => index + 1)
Array.from(Array(100), (v, k) => k + 1)
[...Array(100).keys()]
Copy the code

New Array(100) generates an Array with 100 empty Spaces, which cannot be traversed by map() forEach() filter() reduce() every() some() because empty Spaces will be skipped (for) “Of” does not skip empty Spaces, but traverses them. […new Array(4)] You can set the default value undefined for the empty space so that the Array can be easily traversed.

9. New Map() modifies an attribute value in an array object

Let arr = [{label: 1, placeCode: "sz"}, {label: 2, placeCode: "sz"}, {label: 3, placeCode: "sz"}, "bj" }, { label: 4, placeCode: }] let Map = new Map([['sz', 'sz'],[' sz', 'sz'], 'Beijing ']]) let filterArr = arr => {arr.map(item => item.placecode = maps.get(item.placecode)) return arr} filterArr(arr) / / {label: 1, placeCode: "shenzhen"}, / / {label: 2, placeCode: "shenzhen"}, / / {label: 3, placeCode: "Beijing"}, / / {label: Let toStr = {sz: 'shenzhen ', bj:' Beijing '} arr.map(item => item.placecode = toStr[item.placecode]? toStr[item.placeCode] : item.placeCode)Copy the code

10. PadStart () completes the string

let month = String(new Date().getMonth() + 1).padStart(2, '0')
Copy the code

12. PadEnd () changes the timestamp

Let timetamp = +String(timetamp).padend (13, '0');Copy the code

13. Use deconstruction to remove unnecessary attributes

let {_internal, tooBig, ... cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'}; console.log('cleanObject', cleanObject) // cleanObject {el1: "1", el2: "2", el3: "3"}Copy the code

14. Deconstruct nested objects in function arguments

let car = {
  model: 'bmw 2018',
  engine: {
    v6: true,
    turbo: true,
    vin: 12345
  }
}
const modelAndVIN = ({model, engine: {vin}}) => {
  console.log(`model:${model} vin:${vin}`) // model:bmw 2018 vin:12345
}
modelAndVIN(car)
Copy the code

15. New Map() object optimization (if else/Switch) judgment

The scene of a

Judge the current status of a commodity (1. Opening the group is in progress; 2. Opening the group fails; 3. 5. System cancel)

const actions = new Map([
  [1, ['processing']],
  [2, ['fail']],
  [3, ['fail']],
  [4, ['success']],
  [5, ['cancel']],
  ['default', ['other']]
])
const onButtonClick = status => {
  let action = actions.get(status) || actions.get('default')
  console.log('action', action[0]) // action success
}
onButtonClick(4)
Copy the code

Scenario 2

Judge the current state of a commodity and identify the identity (commodity status is the same as above: Guset guest state master state)

/ / handling a const actions = new Map ([[' guest_1 '() = > console. The log (' guest_1)], [' guest_2', () => console.log('guest_2')], // ... ['master_1', () => console.log('master_1')], ['master_2', () => console.log('master_2')], // ... ['default', () => console.log('default')] ]) const onButtonClick = (identity, status) => { let action = actions.get(`${identity}_${status}`) || actions.get('default') action.call(this) } OnButtonClick ('master', 2) // master_2 // 2 const actions = new Map([[{identity: 'guest', status: 1}, () => console.log('guest_1')], [{identity: 'guest', status: 2}, () => console.log('guest_2')], //... ] ) const onButtonClick = (identity, status) => { let action = [...actions].filter(([key, value]) => key.identity === identity && key.status === status) action.forEach(([key, value]) => value.call(this)) } onButtonClick('guest', 2) // guest_2Copy the code

Scenario 3

What if the processing logic for status 1-4 is the same in the guest case? How to simplify?

const actions = () => { const functionA = () => console.log('this is functionA') const functionB = () => console.log('this is functionB') return new Map([ [/^guest_[1-4]$/, functionA], [/^guest_5$/, functionB] //... ] ) } const onButtonClick = (identity, status) => { let action = [...actions()].filter(([key, value]) => key.test(`${identity}_${status}`)) action.forEach(([key, value]) => value.call(this)) } onButtonClick('guest', 2) // this is functionACopy the code

16. String is cast to a number

Common: Use + to convert a string to a number

+ '123' // 123
+ 'ds' // NaN
+ '' // 0
+ null // 0
+ undefined // NaN
+ {value: () => '3'} // 3
Copy the code

17. Use Boolean to filter out all false values in the array

const compact = arr => arr.filter(Boolean)console.log(compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34])) // [1, 2, 3, "a", "s", 34]
Copy the code

18. The two-bit operator ~~

The two-bit operator replaces math.floor () for positive numbers, math.ceil () for negative numbers, and the double-negative operator is faster because it performs the same operation

Math. Floor (4.9) = = = 4 / / true ~ ~ 4.9 = = = 4 / / true math.h ceil (4.5) / / 4 ~ ~ 4.5 / / 4Copy the code

19. Short-circuit operator

&& for false operation, judging from left to right, if encountered a false value, return false value, no longer execute, otherwise return the last true value

| | to take real operations, judging from left to right in turn, if you meet a true value, and then return true, later no longer perform, otherwise returns a false value finally

/ / variable initialization let variable1 let variable2 = variable1 | | 'foo' / / simply replace the tedious if statements let variable = param && param. PropCopy the code

20. Integer | 0

1.3 | 0 // 1
-1.9 | 0 // -1
Copy the code

21. Judge the odd even number & 1

A numeral &1 can be considered odd or even, and a negative numeral is also considered **, num &1 **

const num = 3 !! (num & 1) // true !! (num % 2) // trueCopy the code

22. How to convert array objects to each other

Let obj = {name: 'xiaoming', age: '24'} let arr = Object.keys(obj).map(key => obj[key]) console.log('arr', arr) // ["xiaoming", "24"] // object.values () object.entries () also allows arrayLike = {'0': 'a', '1': 'b', '2': 'c', length: {'0': 'a', '1': 'b', '2': 'c', length: 3}; let arr = Array.from(arrayLike); console.log(arr); Const arr = [1, 2, 3, 4] const newObj = {... arr} console.log('newObj', newObj) // newObj {0: 1, 1: 2, 2: 3, 3: 4}Copy the code

23. Filter+Reduce Indicates the null value in the Filter object

let obj = { name: null, list: ["1"] } const newObj = Object.keys(obj) .filter(key => obj[key] ! == null) .reduce((prev, curr) => { if (typeof obj[curr] === "object") { prev[curr] = obj[curr].join(",") } return prev }, {}) console.log("newObj", newObj) // newObj {list: "1"}Copy the code

Reference links:

www.zhangxinxu.com/wordpress/2…

Javascript string completion methods padStart() and padEnd()

Blog.csdn.net/qq_40259641…

More elegant writing of JavaScript complex judgments (if else/Switch) optimizes redundancy

Juejin. Cn/post / 684490…

JS tips for increasing happiness

Juejin. Cn/post / 684490…

JS array kit Kat trick