0

0

Array - JavaScript Challenges

花韻仙語

花韻仙語

发布时间:2024-11-02 16:21:50

|

588人浏览过

|

来源于dev.to

转载

array - javascript challenges

您可以在 repo github 上找到这篇文章中的所有代码。

百度AI搜
百度AI搜

百度全新AI搜索引擎

下载

阵列相关的挑战


数组

/**
 * @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<t>>} 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<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 < 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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
github中文官网入口 github中文版官网网页进入
github中文官网入口 github中文版官网网页进入

github中文官网入口https://docs.github.com/zh/get-started,GitHub 是一种基于云的平台,可在其中存储、共享并与他人一起编写代码。 通过将代码存储在GitHub 上的“存储库”中,你可以: “展示或共享”你的工作。 持续“跟踪和管理”对代码的更改。

4387

2026.01.21

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

49

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

88

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

273

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

59

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

99

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

105

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

230

2026.03.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

618

2026.03.04

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 4.2万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.6万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 94人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号