一、代碼簡潔之道18條!

1、將值轉換為數(shù)組

const castArray = value => Array.isArray(value) ? value : [value];
//Examples
castArray(1);              // [1]
castArray([1,2,3]);    // [1,  2,  3]

2、 檢查數(shù)組是否為空

const isEmpty = arr => !Array.isArray(arr) || arr.length === 0;
// Examples
isEmpty([]);      // t rue
isEmpty([1, 2, 3])    // false

3、克隆一個數(shù)組

// `arr` is an array
const clone = arr => arr.slice(0);
// Or 使用擴展運算符
const clone = arr => [...arr];
const clone = arr => Array.from(arr);
const clone = arr => arr.map(x => x);
const clone = arr => JSON.parse(JSON.stringify(arr));
const clone = arr => arr.concat([]);

4、比較兩個數(shù)組

// `a` and `b`  are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
//Examples
isEqual([1, 2, 3], [1, 2, 3]);    // true
isEqual([1, 2, 3], [1, '2', 3]); // false

5、 不管順序比較兩個數(shù)組, 通過sort方法進行排序后進行比較

// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());
// Examples
isEqual([1, 2, 3], [1, 2, 3]);      // true
isEqual([1, 2, 3], [1, 3, 2]);      // false
isEqual([1, 2, 3], [1, '2', 3]); // false

6、將對象數(shù)組轉換為單個對象

const toObject = (arr, key) => arr.reduce((a, b) => ({...a, [b[key]] : b }),  {}); 
toObject(
   [
        [{ id: '1', name: 'Alpha',gender:'Male' }],
        [{ id: '2', name: 'Bravo',gender:'Male' }],
        [{ id: '3', name: 'Charlie',gender:'Female' }]
  ],
  ' id '
)

7、 將字符串數(shù)組轉換為數(shù)字

    const toNumbers = arr => arr.map(Number);
    const toNumbers = arr => arr.map(x => +x);
    // Example
    toNumbers(['2', '3', '4']);    // [2, 3,  4]

8、按對象數(shù)組的屬性計數(shù)

const countBy = (arr, prop) => arr.reduce((prev, curr) => (prev[curr[prop]] = ++ prev[curr[prop]] || 1, prev), {});
//   Example
countBy([
  {  branch: 'audi', model: 'q8', year: '2019'  },
  {  branch: 'audi', model: 'rs7', year: '2020' },
  {  branch: 'ford', model: 'mustang', year: '2019' },
  {  branch: 'ford', model: 'explorer', year: '2020' },
  {  branch: 'bmw', model: 'x7', year: '2020' }
], 'branch')
// {  'audi': 2, 'ford': 2, 'bmw': 1 }

9、計算數(shù)組中某個值的出現(xiàn)次數(shù)

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a+1 :  a), 0);
const countOccurrences = (arr,val) => arr.filter(item => item === val).length;
// Example
countOccurrences ([2, 1, 3, 3, 2, 3], 2);    // 2
countOccurrences (['a', 'b',  'a',  'c', 'a', 'b'],  'a'); //3

10、計算數(shù)組元素的出現(xiàn)冊數(shù)

const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[cuyrr] || 1, prev), {});
// Examples
countOccurrences([2, 1, 3, 3, 2, 3]);       // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']);  // {  'a': 3,  'b': 2,  'c': 1 }

11、創(chuàng)建一個累積和的數(shù)組

const accumulate = arr => arr.map((sum => value => sum += value), (0));
const accumulate = arr => arr.reduce((a, b, i) => i===0 ? [b] : [...a, b + a[i-1]],  []);
const accumulate = arr => arr.reduce((a, b, i) => i === 0 ? [b] : [...a, b + a[i-1]], 0);
//Example
accumulate([1, 2, 3, 4,]);    // [1, 2, 6, 10]

12、創(chuàng)建一個范圍內(nèi)的數(shù)字數(shù)組,先給數(shù)組給定長度,然后獲取下標為數(shù)組內(nèi)值,通過下標加最小值

const range = (min, max) => [...Array(max - min +1).keys()].map(i => i+min);
const range = (min, max) => Array(max - min + 1).fill(0).map((_,  i) => min + i);
const range = (min, max) => Array.from({length: max - min + 1}, (_, i) => min + i);
// Example
range(5, 10);

13、 創(chuàng)建笛卡爾積

const cartesian = (...sets) => sets.reduce((acc, set) => acc.flatMap((x) => set.map((y) => [...x, y])), [[]]);
// Example
cartesian ([1, 2], [3, 4]);      // [  [1, 3], [1, 4], [2, 3], [2, 4] ]

14、 清空數(shù)組

const empty = arr => arr.length = 0;
arr = [];

15、 從數(shù)組中找到最接近的數(shù)字

// Find the number from `arr` which is closest to `n`
const closest = (arr, n) => arr.reduce => arr.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev);
const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - nm))[0];
// Examle
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50);  // 33

16、 查找數(shù)組最后一個匹配項的索引

const lastIndex = (arr, predicate) => arr.reduce((prev, curr, index)) => predicate(curr) ? index : prev, -1);

17、計算兩個日期之間的差異天數(shù)

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
// Example 
diffDays(new Date('2014-12-19'), new Date('2020-01-01')); //1839

18、 計算兩個日期之間的月數(shù)

const monthDiff = (startDate, endDate) => Math.max(0,
 (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
// Example
monthDiff(new Date('2020-01-01'), new Date('2021-01-01'));  // 12
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 本文來自于我的慕課網(wǎng)手記:非常實用的 Java 8 代碼片段,轉載請保留鏈接 ;) Array(數(shù)組相關) chu...
    程序猿天璇閱讀 2,016評論 0 7
  • 一家之言 姑妄言之 絮絮叨叨 不足為訓 ArrayList類注釋翻譯: ?? ArrayList是一個實現(xiàn)了Lis...
    KevenPotter閱讀 834評論 1 3
  • 這篇文章打算詳細理一下HashMap的源碼,可能會比較長,基于JDK1.8 HashMap數(shù)據(jù)結構 HashMap...
    章小傳閱讀 352評論 0 0
  • 第一部分 打好基礎 Laying the Foundation 第一章 歡迎進入軟件構建的世界 Welcome t...
    白樺葉閱讀 4,804評論 0 17
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,855評論 28 54

友情鏈接更多精彩內(nèi)容