Skip to content

Latest commit

 

History

History
57 lines (42 loc) · 1.04 KB

数组操作.md

File metadata and controls

57 lines (42 loc) · 1.04 KB
  • 判断是否是数组
export const isArray = arr => return toString.call(arr) == '[object Array]';
  • 基本类型数组去重
export const uniqueArr = arr => [...new Set(arr)];
  • 数组并集
export const unionArr = (a, b) => [...new Set([...a, ...b])];
  • 数组交集
export const intersectArr = (a, b) => [...new Set([...a].filter(x => b.has(x)))];
  • 数组差集
export const differenceArr = (a, b) => [...new Set([...a].filter(x => !b.has(x)))];
  • 对象数组单个键值匹配去重
export const uniqKeyInArr = (arr, key) => {
 let cache = {};
 return arr.reduceRight((item, next) => {
  cache[next[key]] ? '' : cache[next[key]] = true && item.push(next);
  return item;
 }, []);
}
  • 对象数组完全匹配去重
export const uniqObjInArr = arr =>
    Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
  • 规整多重数组
export const flatten = arr => {
 if (!Array.isArray(arr)) return arr;
 return arr.reduce((done, curr) => done.concat(flatten(curr)), [])
}