- 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前言
我相信每个人的项目中都会有util.js这样的文件,这是我的项目中经常用到的工具函数,但是现在为了方便,直接用的lodash插件,方便快速开发。
判断是否为数组
const isArray = (v) => {
return v instanceof Array || v.constructor === Array || Object.prototype.toString.call(v) == '[object Array]';
}
复制代码
判断一个值是否在数组中
const inArray = (needle, haystack) => {
if (!isArray(haystack)) {
throw Error('the second argument is not a Array');
}
let len = haystack.length;
for (let i = 0; i < len; i++) {
if (haystack[i] === needle) return true;
}
return false;
}
复制代码
判断数组中是否有重值
const arrayIsRepeat = (arr) => {
let hash = {};
for (var i in arr) {
if (hash[arr[i]]) {
return true;
}
hash[arr[i]] = true;
}
return false;
}
复制代码
测试
let arr = [
{
a:1
},
{
a:1
},
{
b:1
}
]
let newArr = arrayIsRepeat(arr);
console.log(newArr)
复制代码
测试结果
true
复制代码
数组去重
const arrayUnique = (arr = []) => {
if (arr.constructor !== Array) {
throw Error('arrayUnique argument is not a Array');
}
let o = {}, r = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].constructor === Object || arr[i].constructor === Array) {
if (!o[JSON.stringify(arr[i]).toString()]) {
o[JSON.stringify(arr[i]).toString()] = true;
r.push(arr[i]);
}
} else {
if (!o[arr[i]]) {
o[arr[i]] = true;
r.push(arr[i]);
}
}
}
return r;
}
复制代码
测试:
let arr = [
{
a:null
},
{
a: 1
},
{
b: 2
},
{
b: 2
},
{
c: 3
}
]
let newArr = arrayUnique(arr);
console.log(newArr)
复制代码
测试结果
计算出数组中的元素出现的次数
function countOccurrences(arr, value) {
return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}
复制代码
检测数值出现次数
const allEqual = arr => arr.every(val => val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
复制代码
其他类型转数组
const castArray = val => (Array.isArray(val) ? val : [val]);
复制代码
指定深度扁平化数组
const flatten = (arr, depth = 1) => arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
复制代码
求数组中的交集
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); };
复制代码