首页 > 【数组方法大合集】原生js数组array常用工具方法大合集

【数组方法大合集】原生js数组array常用工具方法大合集

var array = {/* 数组求和*/sum: arr => eval(arr.join("+")),/* 判断一个数组(支持一个字符串)里面的是否有任何一个元素被包含在了某个字符串里面 */isStringContain(str, arr) {Array.isArray(arr) || (arr = [arr]);for (var i = 0, len = arr.length; i < len; i++) {if (str.includes(arr[i])) return true; //只要有一个元素被包含了就终止循环}return false;},/**获取数组最大值*/getMax(arr) {// 利用apply 将数组元素拆成一个个参数让Math.max去计算// return Math.max.apply(null, arr);  // ES5写法;return Math.max(...arr); // ES6写法;},/**获取数组最小值*/getMin(arr) {// 利用apply 将数组元素拆成一个个参数让Math.min去计算// return Math.min.apply(null, arr);// ES5写法return Math.min(...arr);// ES6写法;},/**判断是否为数组类型*/isArray(o) {return Object.prototype.toString.call(o) == "[object Array]";},/**删除数组中指定元素*/removeFirstByValue(val) {for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];if (a == val) {arr.splice(i, 1);break;}}return arr;/*测试用例*//*var arr = ["mon", "tue", "wed", "thur"];alert(removeFirstByValue(arr, "wed"));*/},/**删除数组中指定匹配的所有元素*/removeAllByValue(val) {var newArr = [];for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];a != val && newArr.push(a);}return newArr;/*测试用例*//*var arr = ["mon", "tue", "wed","wed","wed", "thur"];alert(removeAllByValue(arr, "wed"));*/},/**删除对应键值的→第一个元素*/removeFirstByMatchKey(arr, macthKey, matchKeyValue) {for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];if (a[macthKey] == matchKeyValue) {arr.splice(i, 1);break;}}return arr;},/**删除对应键值的→所有元素*/removeAllByMatchKey(arr, macthKey, matchKeyValue) {var newArr = [];for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];a[macthKey] != matchKeyValue && newArr.push(a);}return newArr;},/**移动数组里面的对应元素step个位置,注意!!!会直接修改原数组*/moveArray(arr, index, step) {/*如step为负数,则往前面移动对应步数。如:-2往前移动两步,3往后移动三步*/var moveToIndex = index + step;moveToIndex < 0 && (moveToIndex = arr.length - 1);moveToIndex > arr.length - 1 && (moveToIndex = 0);arr.splice(moveToIndex, 0, arr.splice(index, 1)[0]);return arr;/*测试用例*//*var arr = ['第一个', '第二个', '第三个', '第四个']; array.moveArray(arr, 1, -2); /!*第二个元素往前移动2步,将会移动到数组最后一个位置*!/ console.log(arr);*/},/**把数组里面的对应元素插入到某个位置,注意!!!会直接修改原数组*/jumpQueue: function (arr, currentIndex, targetIndex) {/*把数组arr里面的currentIndex索引插到targetIndex索引位置*/if (!arr || arr.length === 0) return console.log("%c报错信息:", "background:red;color:white;padding:5px;border-radius:5px;", "arr不能为空");if (currentIndex < 0 || targetIndex < 0 || currentIndex > arr.length - 1 || targetIndex > arr.length - 1) return console.log("%c报错信息:", "background:red;color:white;padding:5px;border-radius:5px;", "currentIndex或者targetIndex超出了arr的索引范围");arr.splice(targetIndex, 0, arr.splice(currentIndex, 1)[0]);return arr;/*测试用例*//*var arr = ['第一个', '第二个', '第三个', '第四个']; array.jumpQueue(arr, 3, 0); /!*第四个元素插队到第一个位置*!/ console.log(arr);*/},/**对比两个数组不同元素,从第一个数组里面排除第二个数组里面相同元素,isAddBdiffPart为true时加入第二个数组不同部分返回结果*/getdiffarr(A, B, isAddBdiffPart) {var C = [];var D = [];var Astr = "," + A.toString() + ",";var Bstr = "," + B.toString() + ",";for (var i in A) {if (!Bstr.includes("," + A[i] + ",")) {C.push(A[i]);}}for (var p in B) {if (!Astr.includes("," + B[p] + ",")) {D.push(B[p]);}}return isAddBdiffPart ? C.concat(D) : C;/*测试用例*//*var F = array.getdiffarr([9, 7, 1, 2, 3, 4], [3, 4, 1, 8], true); console.log(F);*/},/**数组排序:isAsc=true升序;isAsc=false降序*/getSort(arr, isAsc) {var arr = arr.concat();arr.sort(function (a, b) {return isAsc ? a - b : b - a;});return arr;},/**关联数组排序:isAsc=true升序;isAsc=false降序*/getSortByKey(arr, key, isAsc) {var o = arr.concat();o.sort(function (a, b) {return isAsc ? a[key] - b[key] : b[key] - a[key];});return o;},/**数组对象根据某个值相同合并分组(collectKeyName是用于比对合并的键值,addOtherKeys是附加的键值)*/collect(arr, collectKeyName, addOtherKeys) {var map = {}, arr2 = [];for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];if (!map[a[collectKeyName]]) {var obj = {collectName: a[collectKeyName], collectValue: [a]};/*追加可选键值*/var arr3 = addOtherKeys || [];for (var k = 0, len3 = arr3.length; k < len3; k++) {var c = arr3[k];obj[c] = a[c];}arr2.push(obj);map[a[collectKeyName]] = a;} else {for (var j = 0, len2 = arr2.length; j < len2; j++) {var b = arr2[j];if (b.collectName == a[collectKeyName]) {b.collectValue.push(a);break;}}}}return arr2;},/**获取ID→对应的记录*/getById(arr, id) {return this.getByMatchKey(arr, "id", id);},/**获取ID→对应的值*/getValueById(arr, id) {var re = this.getById(arr, id);return re ? re.value : null;},/**获取对应值的→ID*/getIdByValue(arr, value) {var re = this.getByMatchKey(arr, "value", value);return re ? re.id : null;},/**获取对应值的→记录*/getByMatchKey(arr, matchKey, matchKeyValue) {for (var k in arr) {var a = arr[k];if (a && a[matchKey] == matchKeyValue) {return a;}}},/**获取对应值的→键的值*/getValueByMatchKey(arr, matchKey, matchKeyValue, keyName) {var re = this.getByMatchKey(arr, matchKey, matchKeyValue);return re ? re[keyName] : null;},/**设置数组对应ID→对应的key值*/setKeyValueById(arr, id, keyName, keyValue) {this.setValueByMatchKey(arr, "id", id, keyName, keyValue);},/**设置数组对应自定义匹配key→对应的值keyValue*/setValueByMatchKey(arr, matchKey, matchKeyValue, keyName, keyValue) {for (var k in arr) {var a = arr[k];if (a && a[matchKey] == matchKeyValue) {a[keyName] = keyValue;}}},/**根据对应自定义匹配key→对应的值index*/getIndexByMatchKey(arr, matchKey, matchKeyValue) {for (var k in arr) {var a = arr[k];if (a && a[matchKey] == matchKeyValue) {return k; //返回值记得用parseInt()转换为int类型,如果搜索的arr是一个object对象则不用转换值类型,返回的就是key的字符串}}},/**根据value的值获取元素索引值index*/getIndexByValue(arr, value) {return this.getIndexByMatchKey(arr, "value", value);},/**根据id的值获取元素索引值index*/getIndexById(arr, id) {return this.getIndexByMatchKey(arr, "id", id);},/**获取数组对应key→对应的valueKey值(key的格式{key: "id", value: 2, valueKey: "b"}),指定对应id等于2的b字段返回值;valueKey为空时返回整个元素记录*/getkeyValueByKeyValue(arr, key) {for (var k in arr) {var a = arr[k];if (a[key.key] == key.value) {return key.valueKey ? a[key.valueKey] : a;}}/*测试用例*//* console.log(getkeyValueByKeyValue([{id: 1, a: 11, b: 111}, {id: 2, a: 22, b: 222}], {key: "id", value: 2, valueKey: "b"}));*/},/**设置数组对应key→对应的valueKey值(key的格式{key: "id", value: 2, setKey: "b", setValue: "999"}),设置对应id等于2的b字段的值为999*/setkeyValueByKeyValue(arr, key) {for (var k in arr) {var a = arr[k];if (a[key.key] == key.value) {a[key.setKey] = key.setValue;}}return arr;/*测试用例*//* console.log(setkeyValueByKeyValue([{id: 1, a: 11, b: 111}, {id: 2, a: 22, b: 222}], {key: "id", value: 2, setKey: "b", setValue: 999}));*/},/**根据by数组的key对应的值→去from的arr数组里面查询key对应的值相同的项并返回数组,o的结构: { from: { arr: arr1, key: "value", }, by: { arr: arr2, key: "id", } } */getArrayByTwoKey(o) {var reArr = [];var arr1 = o.from.arr, k1 = o.from.key, arr2 = o.by.arr, k2 = o.by.key;for (var i = 0, len = arr2.length; i < len; i++) {var b = arr2[i];arr1.forEach(function (a) {a[k1] == (k2 ? b[k2] : b) && reArr.push(a);});}return reArr;},__convertToKeyValueObject(obj) {for (var i in obj) {var a = obj[i];return {"key": i, "value": a};}},/**模糊搜索key→对应的value值(obj的格式{keyName:keyValue})*/searchArrayByKey(arr, obj) {var reArr = [];obj = this.__convertToKeyValueObject(obj);for (var k in arr) {var a = arr[k];if (a[obj.key].toString().includes(obj.value)) {reArr.push(a);}}return reArr;},/**模糊搜索→全字段值匹配*/searchArrayByValue(arr, value) {var reArr = [];for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];for (var k in a) {var b = a[k];if (b.toString().toLowerCase().includes(value.toLowerCase())) {reArr.push(a);break;}}}return reArr;},/**获取longString字符串中被startStr和end重复夹住的字符串*/getBetween(longString, startStr, endStr) {var arr = longString.split(startStr), reArr = [];arr.shift();for (var i = 0, len = arr.length; i < len; i++) {var a = arr[i];reArr.push(a.split(endStr)[0]);}return reArr;},/**用指定字符串分割将相同元素归类,并返回新的数组*/getSortOutArrayBySplit(arr, splitStr) {var retArr = [], ind = -1, oldValue;for (var i = 0, len = arr.length; i < len; i++) {var newValue = arr[i];oldValue == newValue ? (retArr[ind] = retArr[ind] + (splitStr || "/") + newValue) : (oldValue = newValue, ind++, retArr[ind] = newValue);}return retArr;/* 测试用例var subList = [1, 1, 1, 2, 2, 3, 3];console.log(array.getSortOutArrayBySplit(subList,'/'));//output: ["1/1/1", "2/2", "3/3"];*/},/**去重(效率最高的方法)*/distinct(arr) {var re = [], obj = {};for (var i of arr) {obj[i] || (re.push(i), obj[i] = true);}return re;// return [...new Set(arr)];//去重最精简方法},/** es6语法:过滤JS数组中的空值,假值等(es6语法) */filterNullUndefined: arr => arr.filter(item => item)
//测试用例
//console.log(array.filterNullUndefined([undefined, undefined, 1, "", "false", false, true, null, "null"]));
};

 

更多相关:

  • 题目:最小的k个数 入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。 示例 1: 输入:arr = [3,2,1], k = 2 输出:[1,2] 或者 [2,1] 示例 2: 输入:arr = [0,1,2,1], k = 1 输出:[0...

  • //自定义深度复制对象or数组的递归方法---------------------------------------- let copyObjOrArr = o => {let isArray = o instanceof Array;let isObject = o instanceof Object;if (!isObject)...

  • 经过调研发现,对任意无序整数数组,快速排序有两种实现方法,这里简单阐述下思路: 思路一:随意选择一个基准元,一般选择数组的起始元或末尾元,Weiss这本书上特意搞了个算法来选择基准元,……,总之就是基准元的选择要尽量随机。选定基准元之后,比如选择数组起始元为基准元,从数组右边开始,向左边遍历,遇到比基准元大的跳过,直至遇到比基准元小...

  • 下面给出这段时间我苦心研究验证过的十种经典排序算法的C语言版本,即下面的排序算法: 插入排序,shell排序,冒泡排序,快速排序,选择排序,堆排序,归并排序,桶排序,基数排序和计数排序。整理出来以作备忘,不足之处,欢迎大家批评指正!其中计数排序分别给出了不稳定和稳定两种排序算法,测试时,使用随机生成大数组和随机手动输入的方法来测试。...

  • //获取某一个cookie的值 const getCookie = key => {var k = key, dc = document.cookie;if (dc.length > 0) {var s = dc.indexOf(k + "=");if (s != -1) {s = s + k.length + 1;var e = d...

  • var SGheadMapPoints = {/*obj={ maxLng: minLng: maxLat: minLat: maxCount:最大人数 minCount:最小人数 total:点位数量 }*/get: function (obj) {var arr = [];obj.maxCount || (obj.maxCount...

  • //自动搜索指定的请柬 var alertTipText = "请柬找到了,就在这个网页里面,自己仔细看吧"; var delay = 1 * 1000;//1秒后循环下一页寻找 /*获取子DOM元素在父元素里面的索引位置(是第几个元素)*/ function getNodeListIndex(childNode) {return c...

  •  获取天气情况(不支持跨域) /*json原生获取*/ function getJSON() {var XML;var url = "http://wthrcdn.etouch.cn/weather_mini?city=杭州";if (window.XMLHttpRequest) {XML = new XMLHttpRequest(...

  • /*判断屏幕宽高比是否为16:9*/ function isScreen16to9() {return window.screen.height / window.screen.width === 9 / 16; }...

  • /*关闭、刷新、跳转、离开当前网页前提示*/ onbeforeunload = function () {return false; };  ...

  • let json = {/**判断JSON格式*/ isJSON: function (str) {if (typeof str == "string") {try {var obj = JSON.parse(str);if (typeof obj == "object" && obj) {return true;} else {...

  •   项目结构   index.js //必须要安装否则就别想运行了❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤ //npm i body-parser -D & cnpm i express & cnpm i node-xlsx & cnp...

  • 一、递归 函数    为什么要有函数,提高代码的可读性,避免重复的代码,提高代码的复用性      在函数中能用return的不要print 1、递归的最大深度997 def foo(n):print(n)n+=1foo(n) foo(1) 递归的最大深度 2、修改递归的最大深度     由此我们可以看出,未报错之前能看到的最大数...