关于javascript:面试可能会问的数组操作

42次阅读

共计 7579 个字符,预计需要花费 19 分钟才能阅读完成。

数组去重

数组去重的测试数据如下:

const sourceArray = [null, 6, 34, '6', [], 'a', undefined, 'f', 'a', [], 
34, null, {}, true, NaN, {}, NaN, false, true, undefined
]

const filterArray = unique(sourceArray)

双循环

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]

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

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)返回的永远是 -1,而 index 永远不可能为 -1,所以 NaN 过滤掉了

function unique(sourceData) {let filterArray = []
  sourceData.forEach(item => {
    // filterArray 数组中没有 item
    if (filterArray.indexOf(item) === -1) {filterArray.push(item)
    }
  })
  return filterArray
}
// [null, 6, 34, "6", [], "a", undefined, "f", [], {}, true, NaN, {}, NaN, false]

sort

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、数组、对象等援用数据类型的状况。

includes

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() // 创立 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]

注:以上几个计划不适用于含有数组、对象等援用数据类型的状况。

object

利用对象属性的唯一性去重。

function unique(sourceData) {let map = new Map() // 创立 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 组数字类型的数据,按下面代码编写的程序执行工夫如下:

总结一下:耗时较短的是 set map sort 几个计划,耗时较长的是 reduce 计划,能解决援用数据类型的只有 object 计划。

数组扁平化

数组扁平化的测试数据如下:

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

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 参数阐明
   * 默认:flag() 数组只开展一层
   * 数字:flat(2) 数组开展两层,传入管制开展层数的数字;数字小于等于 0,返回原数组
   * Infinity:flat(Infinity),开展成一维数组
  */
  return sourceArray.flat(Infinity)
}
const flatArray = flat(sourceArray)
// [4, "4", "c", 6, {…}, 7, "v", "s", 6, 23, "叹郁孤"] 

数组并集

数组并集、交加、差集的测试数据如下:

const sourceArray = [
  48, 34, '6', undefined, 'f', 'a',
  34, true, NaN, false, 34, true, 'f'
] 
const sourceArray2 = [
  52, 34, '6', undefined, 's', 23,
  'cf', true, NaN, false, NaN
]

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"]

数组交加

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]

数组差集

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"]

数组宰割

数组宰割测试数据如下:

const sourceArray = [73, 343, 'g', 56, 'j', 10, 32, 43, 90, 'z', 9, 4, 28, 'z', 58, 78, '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 个你不得不晓得的数组 reduce 高级用法 这篇文章的数组宰割办法,乍眼一看可能不太好了解,我略微改了下代码结并加了正文便于了解。原始代码如下:

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), [[]]) : [];}

调整后的代码:

function chunk2(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]有四个数据后[[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"]] 

数组转对象

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: "张鑫旭", price: 69, serialNumber: 'ISBN: 97871151759'},
  {name: "活着", author: "余华", price: 17.5, serialNumber: 'I247.57/105'},
  {name: "资本论", author: "马克思", price: 75, serialNumber: '9787010041155'}
];
function toObject(books) {return books.reduce((pre, cur) => {
    /**
     * ...rest 用于获取残余的解构数据
     * 如:{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}
 * }
*/

参考文章

  • 解锁多种 JavaScript 数组去重姿态
  • 25 个你不得不晓得的数组 reduce 高级用法

正文完
 0