
您可以在 repo github 上找到这篇文章中的所有代码。
阵列相关的挑战
数组
/** * @return {array} */function arrayof(arr) { return [].slice.call(arguments);}// usage exampleconst array1 = [1, 2, 3];const array2 = [4, 5, 6];const combinedarray = arrayof(array1, array2);console.log(combinedarray); // => [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
数组到树
/** * @param {array} arr * @return {array} */function arrtotree(arr) { const tree = []; const hashmap = new map(); // create nodes and store references arr.foreach((item) => { hashmap[item.id] = { id: item.id, name: item.name, children: [], }; }); // build the tree arr.foreach((item) => { if (item.parentid === null) { tree.push(hashmap[item.id]); } else { hashmap[item.parentid].children.push(hashmap[item.id]); } }); return tree;}// usage exampleconst flatarray = [ { id: 1, name: "node 1", parentid: null }, { id: 2, name: "node 1.1", parentid: 1 }, { id: 3, name: "node 1.2", parentid: 1 }, { id: 4, name: "node 1.1.1", parentid: 2 }, { id: 5, name: "node 2", parentid: null }, { id: 6, name: "node 2.1", parentid: 5 }, { id: 7, name: "node 2.2", parentid: 5 },];const tree = arrtotree(flatarray);console.log(tree); // => [{ id: 1, name: 'node 1', children: [ [object], [object] ] }, { id: 5, name: 'node 2', children: [ [object], [object] ] }]
数组包装器
class arraywrapper { constructor(arr) { this._arr = arr; } valueof() { return this._arr.reduce((sum, num) => sum + num, 0); } tostring() { return `[${this._arr.join(",")}]`; }}// usage exampleconst obj1 = new arraywrapper([1, 2]);const obj2 = new arraywrapper([3, 4]);console.log(obj1 + obj2); // => 10console.log(string(obj1)); // => [1,2]
类数组到数组
/** * @param {any} arraylike * @return {array} */function arrayliketoarray(arraylike) { return array.from(arraylike);}// usage exampleconst arraylike = { 0: "a", 1: "b", 2: "c", length: 3,};console.log(arrayliketoarray(arraylike)); // => ['a', 'b', 'c']
块
/** * @template t * @param {array} arr the array to process. * @param {number} [size=1] the length of each chunk. * @returns {array<array>} the new array of chunks. */function chunk(arr, size = 1) { if (!array.isarray(arr) || size < 1) { return []; } const newarray = []; for (let i = 0; i [['a'], ['b'], ['c'], ['d']]console.log(chunk([1, 2, 3, 4], 2)); // => [[1, 2], [3, 4]]console.log(chunk([1, 2, 3, 4], 3)); // => [[1, 2, 3], [4]]
组合
/** * @param {array} arrs * @return {array} */function generatecombinations(arrs) { const result = []; function backtrack(start, current) { if (start === arrs.length) { result.push(current.join('')); return; } for (const item of arrs[start]) { current.push(item); backtrack(start + 1, current); current.pop(); } } backtrack(0, []); return result;}// usage exampleconst nestedarray = [['a', 'b'], [1, 2], [3, 4]];console.log(generatecombinations(nestedarray)); // => ['a13', 'a14', 'a23', 'a24', 'b13', 'b14', 'b23', 'b24']
不同之处
/** * @param {array} array * @param {array} values * @return {array} */function difference(arr, values) { const newarray = []; const valueset = new set(values); for (let i = 0; i [1]console.log(difference([1, 2, 3, 4], [2, 3, 1])); // => [4]console.log(difference([1, 2, 3], [2, 3, 1, 4])); // => []console.log(difference([1, , 3], [1])); // => [3]
立即下降
/** * @param {array} array * @param {function} predicate * @return {array} */function droprightwhile(arr, predicate) { let index = arr.length - 1; while (index >= 0 && predicate(arr[index], index, arr)) { index -= 1; } return arr.slice(0, index + 1);}// usage exampleconsole.log(droprightwhile([1, 2, 3, 4, 5], (value) => value > 3)); // => [1, 2, 3]console.log(droprightwhile([1, 2, 3], (value) => value []console.log(droprightwhile([1, 2, 3, 4, 5], (value) => value > 6)); // => [1, 2, 3, 4, 5]
掉落时
/** * @param {array} array * @param {function} predicate * @return {array} */function dropwhile(arr, predicate) { let index = 0; while (index value [3, 4, 5]dropwhile([1, 2, 3], (value) => value []
展平
/** * @param {array} value * @return {array} */function flatten(arr) { const newarray = []; const copy = [...arr]; while (copy.length) { const item = copy.shift(); if (array.isarray(item)) { copy.unshift(...item); } else { newarray.push(item); } } return newarray;}// usage exampleconsole.log(flatten([1, 2, 3])); // [1, 2, 3]// inner arrays are flattened into a single level.console.log(flatten([1, [2, 3]])); // [1, 2, 3]console.log( flatten([ [1, 2], [3, 4], ])); // [1, 2, 3, 4]// flattens recursively.console.log(flatten([1, [2, [3, [4, [5]]]]])); // [1, 2, 3, 4, 5]
生成唯一的随机数组
/** * @param {number} range * @param {number} outputcount * @return {array} */function generateuniquerandomarray(range, outputcount) { const arr = array.from({ length: range }, (_, i) => i + 1); const result = []; for (let i = 0; i [3, 7, 1, 9, 5]
交叉点
/** * @param {function} iteratee * @param {array[]} arrays * @returns {array} */function intersectionby(iteratee, ...arrs) { if (!arrs.length) { return []; } const mappedarrs = arrs.map((arr) => arr.map(iteratee)); let intersectedvalues = mappedarrs[0].filter((value) => { return mappedarrs.every((mappedarr) => mappedarr.includes(value)); }); intersectedvalues = intersectedvalues.filter((value, index, self) => { return self.indexof(value) === index; }); return intersectedvalues.map((value) => { const index = mappedarrs[0].indexof(value); return arrs[0][index]; });}// usage exampleconst result = intersectionby(math.floor, [1.2, 2.4], [2.5, 3.6]); // => [2.4]console.log(result); // => [2.4]const result2 = intersectionby( (str) => str.tolowercase(), ["apple", "banana", "orange", "orange"], ["apple", "banana", "orange"]);console.log(result2); // => ['apple', 'banana', 'orange']
路口
/** * @param {array[]} arrays - the arrays to find the intersection of. * @returns {array} - an array containing the elements common to all input arrays. */function intersectarrays(...arrs) { if (!arrs.length) { return []; } const set = new set(arrs[0]); for (let i = 1; i { if (!arrs[i].includes(value)) { set.delete(value); } }); } return array.from(set);}// usage exampleconsole.log(intersectarrays([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 6])); // => [3, 4]
意思是
/** * @param {array} array * @return {number} */function mean(arr) { return arr.reduce((sum, number) => sum + number, 0) / arr.length;}// usage exampleconsole.log(mean([1, 2, 3])); // => 2console.log(mean([1, 2, 3, 4, 5])); // => 3
删除重复项
/** * @param {*} arr */function removeduplicates(arr) { return array.from(new set(arr));}// usage exampleconst inputarray = [1, 2, 3, 2, 1, 4, 5, 6, 5, 4];const outputarray = removeduplicates(inputarray);console.log(outputarray); // => [1, 2, 3, 4, 5, 6]
随机播放
/** * @param {any[]} arr * @returns {void} */function shuffle(arr) { if (arr.length < 1) { return []; } for (let i = 0; i [*, *, *, *]
排序方式
/** * @param {array} arr * @param {function} fn * @return {array} */function sortby(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b));}// usage exampleconsole.log(sortby([5, 4, 1, 2, 3], (x) => x)); // => [1, 2, 3, 4, 5]
树到数组
/** * @param {Array} tree * @param {number} parentId * @return {Array} */function treeToArr(tree, parentId = null) { const arr = []; tree.forEach((node) => { const { id, name } = node; arr.push({ id, name, parentId }); // recursive if (node.children && node.children.length > 0) { arr.push(...treeToArr(node.children, id)); } }); return arr;}// Usage exampleconst tree = [ { id: 1, name: "Node 1", children: [ { id: 2, name: "Node 1.1", children: [ { id: 4, name: "Node 1.1.1", children: [], }, ], }, { id: 3, name: "Node 1.2", children: [], }, ], }, { id: 5, name: "Node 2", children: [ { id: 6, name: "Node 2.1", children: [], }, { id: 7, name: "Node 2.2", children: [], }, ], },];const flatArray = treeToArr(tree);console.log(flatArray);/*[ { id: 1, name: 'Node 1', parentId: null }, { id: 2, name: 'Node 1.1', parentId: 1 }, { id: 4, name: 'Node 1.1.1', parentId: 2 }, { id: 3, name: 'Node 1.2', parentId: 1 }, { id: 5, name: 'Node 2', parentId: null }, { id: 6, name: 'Node 2.1', parentId: 5 }, { id: 7, name: 'Node 2.2', parentId: 5 }]*/
参考
2695。数组包装器 – leetcode2677。块数组 – leetcode2724。排序依据 – leetcode2625。展平深度嵌套数组 – leetcode131。实现 _.chunk() – bfe.dev8.你能 shuffle() 一个数组吗? – bfe.dev384。随机排列数组 – leetcode138。两个排序数组的交集 – bfe.dev167。未排序数组的交集 – bfe.dev66。从数组中删除重复项 – bfe.dev
以上就是Array – JavaScript Challenges的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1495178.html
微信扫一扫
支付宝扫一扫