常用数组方法
计算一串字符串每个字母出现的次数
var arrString = 'abcdaabddcca'; arrString.split('').reduce(function (prev, curr) { prev[curr] ? prev[curr]++ : prev[curr] = 1; return prev; }, []);
sort排序(json 数组 根据某一属性排序, 倒序)
// const arrB = arrA.sort(sortByKey); function sortByKey (a,b) { return b.time - a.time; }
深拷贝
var deepClone = function (obj) { var _tmp,result; _tmp = JSON.stringify(obj); result = JSON.parse(_tmp); return result; } b = deepClone(a);
数组如何随机排序
function randomSort(a){ var arr = a, random = [], len = arr.length; for (var i = 0; i < len; i++) { var index = Math.floor(Math.random()*(len - i)); random.push(a[index]); arr.splice(index,1); } return random; } var a = [1,2,3,4,5,6,7,8,9,10]; console.log(randomSort(a));
数组去重
function uniq(array){ var temp = []; //一个新的临时数组 for(var i = 0; i < array.length; i++){ if(temp.indexOf(array[i]) == -1){ temp.push(array[i]); } } return temp; } var aa = [1,2,2,4,9,6,7,5,2,3,5,6,5]; console.log(uniq(aa));
ES6 数组去重的一种写法
function dedupe(array) { return Array.from(new Set(array)); } dedupe([1, 1, 2, 3])
普通1维数组并集
function aAddB (a, b) { return [...a, ...b]; } aAddB([1,2,3],[2,3,4]);
普通1维数组交集
function aAndB (a, b) { let intersectionSet = a.filter(x => new Set(b).has(x)); return intersectionSet; } aAndB([1,2,3,4],[2,3,4,5]);
普通1维数组a-b差集
function aNotB (a, b) { let differenceABSet = a.filter(x => !new Set(b).has(x)); return differenceABSet; } aNotB([1,2,3,4],[2,3,4,5]);
普通1维数组并集(ES6去重)
function aAddBRemoveDuplicates (a, b) { return Array.from(new Set([...a, ...b])); } aAddBRemoveDuplicates([1,2,3,4], [2,3,4,5]); //[1, 2, 3, 4, 5]
第二种
function distinct(a, b) { let arr = a.concat(b) let result = [] let obj = {} for (let i of arr) { if (!obj[i]) { result.push(i) obj[i] = 1 } } return result }
JSON数组(一维)根据主key(id等)去重
function unique (arr, key) { var r = []; for (var i = 0, l = arr.length; i < l; i++) { for (var j = i + 1; j < l; j++) { if (key) { if (arr[i][key] === arr[j][key]) { j = ++i; } } else { if (arr[i] === arr[j]) { j = ++i; } } } r.push(arr[i]); } return r; }; let paylist = [ {chnlNo: "现金", amount: 300, type: 2}, {chnlNo: "支付宝", amount: "100", type: 2}, {chnlNo: "银行卡", amount: "400", type: 2}, {chnlNo: "现金", amount: 200, type: 2} ]; unique(paylist,'chnlNo');