您可以在 repo Github 上找到这篇文章中的所有代码。
阵列相关的挑战
数组
/** * @return {Array} */ function arrayOf(arr) { return [].slice.call(arguments); } // Usage example const 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 example const 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 example const obj1 = new ArrayWrapper([1, 2]); const obj2 = new ArrayWrapper([3, 4]); console.log(obj1 + obj2); // => 10 console.log(String(obj1)); // => [1,2]
类数组到数组
/** * @param {any} arrayLike * @return {Array} */ function arrayLikeToArray(arrayLike) { return Array.from(arrayLike); } // Usage example const arrayLike = { 0: "a", 1: "b", 2: "c", length: 3, }; console.log(arrayLikeToArray(arrayLike)); // => ['a', 'b', 'c']
块
/** * @template T * @param {Array<t>} 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 [['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]] </array></t>
组合
/** * @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 example const 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 example console.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 example console.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 example const 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<unknown>[]} arrays - The arrays to find the intersection of. * @returns {Array<unknown>} - 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 example console.log(intersectArrays([1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 6])); // => [3, 4] </unknown></unknown>
意思是
/** * @param {Array} array * @return {Number} */ function mean(arr) { return arr.reduce((sum, number) => sum + number, 0) / arr.length; } // Usage example console.log(mean([1, 2, 3])); // => 2 console.log(mean([1, 2, 3, 4, 5])); // => 3
删除重复项
/** * @param {*} arr */ function removeDuplicates(arr) { return Array.from(new Set(arr)); } // Usage example const 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 [*, *, *, *]
排序方式
/** * @param {Array} arr * @param {Function} fn * @return {Array} */ function sortBy(arr, fn) { return arr.sort((a, b) => fn(a) - fn(b)); } // Usage example console.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 example const 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。数组包装器 - LeetCode
- 2677。块数组 - LeetCode
- 2724。排序依据 - LeetCode
- 2625。展平深度嵌套数组 - LeetCode
- 131。实现 _.chunk() - BFE.dev
- 8.你能 shuffle() 一个数组吗? - BFE.dev
- 384。随机排列数组 - LeetCode
- 138。两个排序数组的交集 - BFE.dev
- 167。未排序数组的交集 - BFE.dev
- 66。从数组中删除重复项 - BFE.dev
以上是数组 - JavaScript 挑战的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

10款趣味横生的jQuery游戏插件,让您的网站更具吸引力,提升用户粘性!虽然Flash仍然是开发休闲网页游戏的最佳软件,但jQuery也能创造出令人惊喜的效果,虽然无法与纯动作Flash游戏媲美,但在某些情况下,您也能在浏览器中获得意想不到的乐趣。 jQuery井字棋游戏 游戏编程的“Hello world”,现在有了jQuery版本。 源码 jQuery疯狂填词游戏 这是一个填空游戏,由于不知道单词的上下文,可能会产生一些古怪的结果。 源码 jQuery扫雷游戏

本教程演示了如何使用jQuery创建迷人的视差背景效果。 我们将构建一个带有分层图像的标题横幅,从而创造出令人惊叹的视觉深度。 更新的插件可与JQuery 1.6.4及更高版本一起使用。 下载

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

Matter.js是一个用JavaScript编写的2D刚体物理引擎。此库可以帮助您轻松地在浏览器中模拟2D物理。它提供了许多功能,例如创建刚体并为其分配质量、面积或密度等物理属性的能力。您还可以模拟不同类型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流浏览器。此外,它也适用于移动设备,因为它可以检测触摸并具有响应能力。所有这些功能都使其值得您投入时间学习如何使用该引擎,因为这样您就可以轻松创建基于物理的2D游戏或模拟。在本教程中,我将介绍此库的基础知识,包括其安装和用法,并提供一

本文演示了如何使用jQuery和ajax自动每5秒自动刷新DIV的内容。 该示例从RSS提要中获取并显示了最新的博客文章以及最后的刷新时间戳。 加载图像是选择


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 Linux新版
SublimeText3 Linux最新版

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具