首页 web前端 js教程 数组 - JavaScript 挑战

数组 - JavaScript 挑战

Nov 05, 2024 pm 03:54 PM

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<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

以上是数组 - JavaScript 挑战的详细内容。更多信息请关注PHP中文网其他相关文章!

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1670
14
CakePHP 教程
1428
52
Laravel 教程
1329
25
PHP教程
1276
29
C# 教程
1256
24
Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C到JavaScript:所有工作方式 从C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在行动中:现实世界中的示例和项目 JavaScript在行动中:现实世界中的示例和项目 Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

了解JavaScript引擎:实施详细信息 了解JavaScript引擎:实施详细信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:社区,图书馆和资源 Python vs. JavaScript:社区,图书馆和资源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python vs. JavaScript:开发环境和工具 Python vs. JavaScript:开发环境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

C/C在JavaScript口译员和编译器中的作用 C/C在JavaScript口译员和编译器中的作用 Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

See all articles