Array - JavaScript Challenges
来源:dev.to
2024-11-24 13:06:40
0浏览
收藏
一分耕耘,一分收获!既然都打开这篇《Array - JavaScript Challenges》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新文章相关的内容,希望对大家都有所帮助!

您可以在 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} arr the array to process.
* @param {number} [size=1] the length of each chunk.
* @returns {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 < arr.length; i += size) {
const chunk = arr.slice(i, i + size);
newarray.push(chunk);
}
return newarray;
}
// usage example
console.log(chunk(["a", "b", "c", "d"])); // => [['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 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 < arr.length; i += 1) {
const value = arr[i];
if (
!valueset.has(value) &&
!(value === undefined && !object.hasown(arr, i))
) {
newarray.push(value);
}
}
return newarray;
}
// usage example
console.log(difference([1, 2, 3], [2, 3])); // => [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 < 6)); // => []
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 < arr.length && predicate(arr[index], index, arr)) {
index += 1;
}
return arr.slice(index);
}
// usage example
dropwhile([1, 2, 3, 4, 5], (value) => value < 3); // => [3, 4, 5]
dropwhile([1, 2, 3], (value) => value < 6); // => []
展平
/**
* @param {array<*|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 < outputcount; i += 1) {
const randomindex = math.floor(math.random() * arr.length);
result.push(arr[randomindex]);
arr[randomindex] = arr.at(-1);
arr.pop();
}
return result;
}
// usage example
const uniquerandomnumbers = generateuniquerandomarray(10, 5);
console.log(uniquerandomnumbers); // => [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[]} 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 < arrs.length; i += 1) {
set.foreach((value) => {
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]
意思是
/**
* @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 < 1) {
return [];
}
for (let i = 0; i < arr.length; i += 1) {
const randidx = math.floor(math.random() * (i + 1));
[arr[randidx], arr[i]] = [arr[i], arr[randidx]];
}
return arr;
}
// usage example
console.log(shuffle([1, 2, 3, 4])); // => [*, *, *, *]
排序方式
/**
* @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
理论要掌握,实操不能落!以上关于《Array - JavaScript Challenges》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
电脑怎么禁止锁屏 win11系统禁止锁定屏幕的方法教程
- 上一篇
- 电脑怎么禁止锁屏 win11系统禁止锁定屏幕的方法教程
- 下一篇
- 学员与保卫星球法典
查看更多
最新文章
-
- 文章 · 前端 | 3天前 | 前端 · 性能优化 · css · Core Web Vitals · 渲染性能 · 前端 渲染性能 CSS性能 CLS content-visibility contain-intrinsic-size Layout
- 前端长页面渲染卡顿怎么排查:用 content-visibility 跳过离屏区块
- 430浏览 收藏
-
- 文章 · 前端 | 1星期前 | 前端 · javascript · AbortController · 表单提交 · AbortController 旧响应覆盖 前端重复提交 loading锁 fetch取消 按钮防抖
- 前端按钮重复提交怎么办:loading 锁和 AbortController 最小配方
- 442浏览 收藏
-
- 文章 · 前端 | 1星期前 | 前端 · 缓存 · Service Worker · 白屏 · 发布故障 · 缓存策略 前端白屏 Service Worker CacheStorage 资源404 发布回滚
- 前端发布后白屏复盘:Service Worker 缓存旧入口导致 JS 资源 404
- 469浏览 收藏
-
- 文章 · 前端 | 1星期前 | 前端开发 · localStorage · 表格配置 · 用户偏好 · 后台系统 · 用户偏好 localStorage 前端表格 列配置 可见列 列宽保存
- 前端表格列设置刷新后丢失怎么办:可见列、列宽和顺序这样保存
- 351浏览 收藏
-
- 文章 · 前端 | 1星期前 | 前端 · 接口排查 · 运维手册 · 性能告警 · 前端 AbortController 接口超时 Network瀑布图 降级回滚 线上告警
- 前端接口超时告警运行手册:从瀑布图到降级回滚
- 287浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ljg-skills
- ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
- 4415次使用
-
- MELO音乐
- MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
- 4073次使用
-
- UniScribe
- UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
- 4058次使用
-
- 剧云
- 剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
- 4242次使用
-
- 万象有声
- 万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
- 4217次使用
查看更多
相关文章
-
- JavaScript函数定义及示例详解
- 2025-05-11 502浏览
-
- CSS变量简化按钮悬停效果技巧
- 2026-05-31 501浏览
-
- JavaScript符号类型详解与应用
- 2026-05-31 501浏览
-
- HTML剪贴板复制粘贴怎么用
- 2026-05-26 501浏览
-
- data-*属性详解:HTML数据存储与DOM操作技巧
- 2026-05-25 501浏览

