个人博客:http://blog.lvxiang.site/JS常用小功能/
目录
正文
-
数组去重(es6)
const arr = ['?', 7, '?', '?']; // 1.Set [...new Set(arr)]; // 或者 Array.from(new Set(arr)); // 2.Filter arr.filter((item, index) => arr.indexOf(item) === index); // 3.Reduce /* reducer 函数接收4个参数: 1.Accumulator (acc) (累计器) 2.Current Value (cur) (当前值) 3.Current Index (idx) (当前索引) 4.Source Array (src) (源数组) */ arr.reduce((acc, cur) => return acc.includes(cur) ? acc : [...acc, cur], []); // 4.Object 键值对 array.filter(function(item, index, array){ return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true) }) // 5.Map const seen = new Map() arr.filter((a) => !seen.has(a) && seen.set(a, 1))
-
字符串反转
const str = 'abcdef123'; console.log(str.split('').reverse().join(''));
-
数组去扁平化并去重排序
var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]; Array.from(new Set(arr.flat(Infinity))).sort((a,b)=>{ return a-b})
-
判断数组的方法
const arr = []; // 1. Array对象方法 Array.isArray(arr); //true // 2. instanceof arr instanceof Array; //true // 3.constructor arr.constructor.name === 'Array'; // true // 4.Obecjt的toString方法 Object.prototype.toString.call(arr) === '[object Array]'; //true
-
数组并集、交集、差集
var arr1 = [1,2,3,4];
var arr2 = [2,4,6,8];
// 使用includes
var union = arr1.concat(arr2.filter(v => !arr1.includes(v))); // 并集
console.log(union);
var intersection = arr1.filter(v=> arr2.includes(v)); // 交集
console.log(intersection);
var difference = arr1.concat(arr2).filter(v => !arr1.includes(v) || !arr2.includes(v)); // 差集
console.log(difference);
// 使用set
var setA = new Set(arr1);
var setB = new Set(arr2);
var union1 = Array.from(new Set(arr1.concat(arr2)));
var union2 = Array.from(new Set([...arr1,...arr2]));
console.log(union1); // [1, 2, 3, 4, 6, 8]
console.log(union2); // [1, 2, 3, 4, 6, 8]
var intersection1 = arr1.filter(v=> setB.has(v));
console.log(intersection1);
var difference1 = arr1.concat(arr2).filter(v => !setA.has(v) || !setB.has(v));
console.log(difference1);