Array - JavaScript Challenges

花韻仙語

花韻仙語

2024-11-02

588人浏览

转载

array - javascript challenges

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

度加AI
度加AI

度加AI官网入口,百度官方 AIGC 创作平台,支持 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>>} 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

Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

git 排列

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

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

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

2026.01.21

7576

27

GitHub官网入口版本汇总
GitHub官网入口版本汇总

本专题整合了GitHub入口版本地址汇总,阅读专题下面的文章了解更多详细内容。

2026.04.02

451

19

火山引擎API接入教程
火山引擎API接入教程

火山引擎API接入适合需要在应用、脚本、后台服务或AI工具中调用火山引擎能力的开发者参考。本专题整理控制台入口、服务开通、API Key获取、接口地址配置、请求参数填写、调用测试、权限设置、额度查询和常见接口报错排查。

2026.08.04

0

10

火山引擎DeepSeek API调用教程
火山引擎DeepSeek API调用教程

火山引擎DeepSeek API适合需要在应用、脚本、智能体或AI编程工具中调用DeepSeek模型的开发者参考。本专题整理火山引擎控制台入口、模型服务开通、API Key获取、Base URL配置、模型名称填写、调用测试、额度查询和常见接口报错排查。

2026.08.04

0

10

火山引擎控制台操作教程
火山引擎控制台操作教程

火山引擎控制台中常用功能包括API密钥管理、模型调用配置、云资源查看、账单明细、用量统计和权限分配。本专题整理控制台基础操作、服务开通流程、Key创建与保存、费用消耗查看、子账号权限设置和调用失败排查,方便开发者完成日常管理。

2026.08.04

0

10

PDF与PPT格式转换操作方法及在线转换技巧
PDF与PPT格式转换操作方法及在线转换技巧

本专题聚焦 PDF 与 PPT 文件格式转换需求,整理 PDF 转 PPT 在线转换方法、PPT 批量转换 PDF 操作步骤、转换后格式错乱处理以及文档版式检查技巧。通过详细教程帮助用户掌握 PDF、PPT 双向转换方法,解决演示文稿制作、文件整理和办公格式转换中的常见问题,提高办公效率。

2026.07.31

112

6

PDF合并文件操作方法与在线批量合并技巧
PDF合并文件操作方法与在线批量合并技巧

本专题聚焦 PDF 文件合并与文档整理需求,整理多个 PDF 合并成一个文件、图片批量转换 PDF、合同附件合并发送以及在线 PDF 合并操作方法等实用教程。通过详细步骤介绍 PDF 合并流程、文件顺序检查技巧和免费在线合并方案,帮助用户快速整理零散文档,提高办公文件处理效率。

2026.07.31

86

8

PDF转Word在线转换与文档编辑处理方法
PDF转Word在线转换与文档编辑处理方法

本专题聚焦 PDF 转 Word 文件转换与办公文档处理需求,整理 PDF 在线转换成 Word、PDF 转可编辑 Word、PDF 文件格式转换操作步骤以及转换后版式错乱、图片无法编辑等常见问题解决方法。通过详细教程帮助用户快速掌握 PDF 转 Word 技巧,提高办公文件处理效率。

2026.07.31

87

5

CodeIgniter下载教程
CodeIgniter下载教程

本合集由PHP中文网精心整理,为您提供CodeIgniter下载教程与官方正版下载安装指南。内容涵盖CI3/CI4官方获取渠道、Composer依赖安装及环境配置全流程。助您安全、高效地搭建轻量级PHP框架,轻松开启Web应用开发之旅。

2026.07.30

116

10

热门下载

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

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
vscode手册
vscode手册

共0课时 | 0人学习

Git 教程
Git 教程

共21课时 | 7.4万人学习

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

共8课时 | 1.7万人学习