<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          面試官會問到的數(shù)組操作

          共 17843字,需瀏覽 36分鐘

           ·

          2021-08-03 14:52

          點擊上方 前端瓶子君,關(guān)注公眾號

          回復(fù)算法,加入前端編程面試算法每日一題群

          數(shù)組去重

          數(shù)組去重的測試數(shù)據(jù)如下:

          const sourceArray = [
          null634'6', [], 'a'undefined'f''a', [], 
          34null, {}, trueNaN, {}, NaNfalsetrueundefined
          ]

          const filterArray = unique(sourceArray)

          雙循環(huán)

          image.png
          function unique(sourceData{
            let flag
            let filterArray = []
            for (let i = 0; i < sourceData.length; i++) {
              flag = true 
              for (let j = 0; j < filterArray.length; j++) {
                if (sourceData[i] === filterArray[j]) {
                  flag = false
                  break
                }
              }
              if (flag) {
                filterArray.push(sourceData[i])
              }
            }
            return filterArray
          }
          // [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, NaN, {}, NaN, false]
          image.png
          function unique(sourceData{
            let flag
            let filterArray = []
            for (let i = 0; i < sourceData.length; i++) {
              flag = true 
              for (let j = i + 1; j < sourceData.length; j++) {
                if (sourceData[i] === sourceData[j]) {
                  flag = false
                  break
                }
              }
              if (flag) {
                filterArray.push(sourceData[i])
              }
            }
            return filterArray
          }
          // [6, "6", [], "f", "a", [], 34, null, {}, NaN, {}, NaN, false, true, undefined]

          indexOf

          image.png
          function unique(sourceData{
            return sourceData.filter((item, index) => {
              return sourceData.indexOf(item) === index
            })
          }
          // [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, {}, false]

          注:用sourceData.indexOf(NaN)返回的永遠(yuǎn)是-1,而index永遠(yuǎn)不可能為-1,所以NaN過濾掉了

          1624948470(1).jpg
          function unique(sourceData{
            let filterArray = []
            sourceData.forEach(item => {
              // filterArray數(shù)組中沒有item
              if (filterArray.indexOf(item) === -1) {
                filterArray.push(item)
              }
            })
            return filterArray
          }
          // [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, NaN, {}, NaN, false]

          sort

          image.png
          function unique(sourceData{
            let filterArray = []
            sourceData.sort()
            for (let i = 0; i < sourceData.length; i++) {
              if (sourceData[i] !== filterArray[filterArray.length - 1]) {
                filterArray.push(sourceData[i])
              }
            }
            return filterArray
          }
          // [[], [], 34, 6, "6", NaN, NaN, {}, {}, "a", "f", false, null, true, undefined]

          注:以上幾個方案都不適用于含有NaN、數(shù)組、對象等引用數(shù)據(jù)類型的情況。

          includes

          image.png
          function unique(sourceData{
            let filterArray = []
            sourceData.forEach(item => {
              if (!filterArray.includes(item)) {
                filterArray.push(item)
              }
            })
            return filterArray
          }
          // [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]

          reduce

          function unique(sourceData = []{
            return sourceData.reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], [])
          }
          // [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]

          map

          function unique(sourceData{
            let map = new Map() // 創(chuàng)建Map實例
            return sourceData.filter(item => {
              return !map.has(item) && map.set(item, 1)
            })
          }
          // [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]

          set

          function unique10(sourceData{
            return [...new Set(sourceData)]
          }
          // [[], [], 34, 6, "6", NaN, {}, {}, "a", "f", false, null, true, undefined]

          注:以上幾個方案不適用于含有數(shù)組、對象等引用數(shù)據(jù)類型的情況。

          object

          利用對象屬性的唯一性去重。

          function unique(sourceData{
            let map = new Map() // 創(chuàng)建Map實例
            let filterArray = []
            for (let i = 0; i < sourceData.length; i++) {
              /** 
               * 為什么要使用JSON.stringify()
               * typeof sourceData[i] + sourceData[i] 拼接字符串時可能存在[object Object]
              */

              if (!map[typeof sourceData[i] + JSON.stringify(sourceData[i])]) {
                map[typeof sourceData[i] + JSON.stringify(sourceData[i])] = true;
                filterArray.push(sourceData[i]);
              }
            }
            return filterArray
          }
          // [[], 34, 6, "6", NaN, {}, "a", "f", false, null, true, undefined]

          隨機生成了10000組數(shù)字類型的數(shù)據(jù),按上面代碼編寫的順序執(zhí)行時間如下:

          image.png

          總結(jié)一下:耗時較短的是 set map sort 幾個方案,耗時較長的是 reduce 方案,能處理引用數(shù)據(jù)類型的只有 object 方案。

          數(shù)組扁平化

          數(shù)組扁平化的測試數(shù)據(jù)如下:

          const sourceArray = [4'4', ['c'6], {}, [7, ['v']], ['s', [623, ['嘆郁孤']]]]

          concat + 遞歸

          function flat(sourceArray, flatArray{
            sourceArray.forEach(item => {
              Array.isArray(item) ? flatArray.concat(flat(item, flatArray)) : flatArray.push(item)
            });
            return flatArray
          }
          const flatArray = flat(sourceArray, [])
          // [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "嘆郁孤"]

          ... + 遞歸

          function flat(sourceArray{
            while (sourceArray.some(item => Array.isArray(item))) {
              sourceArray = [].concat(...sourceArray);
            }
            return sourceArray;
          }
          const flatArray = flat(sourceArray)
          // [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "嘆郁孤"]

          reduce + 遞歸

          function flat(sourceArray{
            return sourceArray.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? flat3(cur) : cur), [])
          }
          const flatArray = flat(sourceArray)
          // [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "嘆郁孤"]

          flat

          function flat(sourceArray{
             /**
             * flat參數(shù)說明
             * 默認(rèn):flag() 數(shù)組只展開一層
             * 數(shù)字:flat(2) 數(shù)組展開兩層,傳入控制展開層數(shù)的數(shù)字;數(shù)字小于等于0,返回原數(shù)組
             * Infinity:flat(Infinity),展開成一維數(shù)組
            */

            return sourceArray.flat(Infinity)
          }
          const flatArray = flat(sourceArray)
          // [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "嘆郁孤"] 

          數(shù)組并集

          數(shù)組并集、交集、差集的測試數(shù)據(jù)如下:

          const sourceArray = [
            4834'6'undefined'f''a',
            34trueNaNfalse34true'f'

          const sourceArray2 = [
            5234'6'undefined's'23,
            'cf'trueNaNfalseNaN
          ]

          filter + includes

          function union(sourceArray, sourceArray2{
            const unionArray = sourceArray.concat(sourceArray2.filter(item => !sourceArray.includes(item)))
            return [...new Set(unionArray)]
          }
          const unionArray = union(sourceArray, sourceArray2)
          // [48, 34, "6", undefined, "f", "a", true, NaN, false, 52, "s", 23, "cf"]

          set

          function union(sourceArray, sourceArray2{
            return [...new Set([...sourceArray, ...sourceArray2])]
          }
          const unionArray = union(sourceArray, sourceArray2)
          // [48, 34, "6", undefined, "f", "a", true, NaN, false, 52, "s", 23, "cf"]

          數(shù)組交集

          filter + includes

          function intersect(sourceArray, sourceArray2{
            const intersectArray = sourceArray.filter(item => sourceArray2.includes(item))
            return [...new Set(intersectArray)]
          }
          const intersectArray = intersect(sourceArray, sourceArray2)
          // [34, "6", undefined, true, NaN, false]

          set

          function intersect(sourceArray, sourceArray2{
            sourceArray = new Set(sourceArray)
            sourceArray2 = new Set(sourceArray2)
            const intersectArray = [...sourceArray].filter(item => sourceArray2.has(item))
            return [...new Set(intersectArray)]
          }
          const intersectArray = intersect(sourceArray, sourceArray2)
          // [34, "6", undefined, true, NaN, false]

          數(shù)組差集

          filter + includes

          function difference(sourceArray, sourceArray2{
            const differenceArray = sourceArray.concat(sourceArray2)
              .filter(item => !sourceArray2.includes(item))
            return [...new Set(differenceArray)]
          }
          const differenceArray = difference(sourceArray, sourceArray2)
          // [48, "f", "a"]

          set

          function difference(sourceArray, sourceArray2{
            sourceArray = new Set(sourceArray)
            sourceArray2 = new Set(sourceArray2)
            const intersectArray = [...sourceArray].filter(item => !sourceArray2.has(item))
            return [...new Set(intersectArray)]
          }
          const differenceArray = difference(sourceArray, sourceArray2)
          // [48, "f", "a"]

          數(shù)組分割

          數(shù)組分割測試數(shù)據(jù)如下:

          const sourceArray = [73343'g'56'j'10324390'z'9428'z'5878'h']

          const chunkArray = chunk(sourceArray, 4)

          while + slice

          function chunk(sourceArray = [], length = 1{
            let chunkArray = []
            let index = 0
            while (index < sourceArray.length) {
              chunkArray.push(sourceArray.slice(index, index += length))
            }
            return chunkArray
          }
          const chunkArray = chunk(sourceArray, 4)
          // [[73, 343, "g", 56], ["j", 10, 32, 43], [90, "z", 9, 4], [28, "z", 58, 78], ["h"]]

          reduce

          以下是出自 25個你不得不知道的數(shù)組reduce高級用法 這篇文章的數(shù)組分割方法,乍眼一看可能不太好理解,我稍微改了下代碼結(jié)并加了注釋便于理解。原始代碼如下:

          function chunk(arr = [], size = 1{
              return arr.length ? arr.reduce((t, v) => (t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v), t), [[]]) : [];
          }

          調(diào)整后的代碼:

          function chunk(arr = [], size = 1{
            if (arr.length) {
              arr = arr.reduce((t, v) => {
              /**
                 * t的初始值為[[]],這時t.length為1,所以t[t.length - 1]為[],t[t.length - 1].length為0,將v push到t[0]中,此時t = [[73]]
                 * 這時t.length還是為1,所以t[t.length - 1]為[73],t[t.length - 1].length為1,將v push到t[0]中,此時t = [[73, 343]]
                 * 直到t[0]有四個數(shù)據(jù)后[[73, 343, "g", 56]]
                 * 這時t.length為1,所以t[t.length - 1]為[73, 343, "g", 56],t[t.length - 1].length為4,將[v] push到t中,此時t = [[73, 343, "g", 56]['j']],以此類推
                */

                t[t.length - 1].length === size ? t.push([v]) : t[t.length - 1].push(v)
                return t
              }, [[]])
            }
            return arr
          }
          // [[73, 343, "g", 56], ["j", 10, 32, 43], [90, "z", 9, 4], [28, "z", 58, 78], ["h"]] 

          數(shù)組轉(zhuǎn)對象

          Object.assign

          const sourceArray = ['CSS世界''活著''資本論']
          function toObject(sourceArray{
            return Object.assign({}, sourceArray)
          }
          const result = toObject(sourceArray)
          // {0: "CSS世界", 1: "活著", 2: "資本論"}

          reduce

          第一種對象形式

          const books = [
            { name"CSS世界"author"張鑫旭"price69serialNumber'ISBN: 97871151759' },
            { name"活著"author"余華"price17.5serialNumber'I247.57/105' },
            { name"資本論"author"馬克思"price75serialNumber'9787010041155' }
          ];
          function toObject(books{
            return books.reduce((pre, cur) => {
              /**
               * ...rest用于獲取剩余的解構(gòu)數(shù)據(jù)
               * 如:{ name: "CSS世界", author: "張鑫旭", price: 69 }
              */

              const { serialNumber, ...rest } = cur;
              pre[serialNumber] = rest;
              return pre;
            }, {});
          }
          const map = toObject(books)
          /**
           * {
           *   ISBN: 97871151759: {name: "CSS世界", author: "張鑫旭", price: 69}, 
           *   I247.57/105: {name: "活著", author: "余華", price: 17.5}, 
           *   9787010041155: {name: "資本論", author: "馬克思", price: 75}
           * }
          */

          第二種對象形式

          // 方案一
          const person = [
            { name"Siri"age22 },
            { name"Bob"age20 },
            { name"Tom"age21 }
          ];
          function toObject(person{
            return person.reduce((pre, cur) => (pre[cur.name] = cur.age, pre), {})
          }
          const result = toObject(person)
          // {Siri: 22, Bob: 20, Tom: 21}

          // 方案二
          function toObject2(person{
            return person.reduce((pre, cur) => ({...pre, [cur.name]: cur.age}), {})
          }
          const result = toObject2(person)
          // {Siri: 22, Bob: 20, Tom: 21}

          參考文章

          • 解鎖多種JavaScript數(shù)組去重姿勢
          • 25個你不得不知道的數(shù)組reduce高級用法


          關(guān)于本文

          來源:廢廢

          https://segmentfault.com/a/1190000040273511


          最后

          歡迎關(guān)注【前端瓶子君】??ヽ(°▽°)ノ?
          回復(fù)「算法」,加入前端編程源碼算法群,每日一道面試題(工作日),第二天瓶子君都會很認(rèn)真的解答喲!
          回復(fù)「交流」,吹吹水、聊聊技術(shù)、吐吐槽!
          回復(fù)「閱讀」,每日刷刷高質(zhì)量好文!
          如果這篇文章對你有幫助,在看」是最大的支持
           》》面試官也在看的算法資料《《
          “在看和轉(zhuǎn)發(fā)”就是最大的支持
          瀏覽 30
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  蜜桃91在线观看 | 国产少又黄又爽的A片 | 观看免费A片 | 人人干人人干 | 中文字幕手机在线观看 |