0

0

Array - JavaScript Challenges

花韻仙語

花韻仙語

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

|

588人浏览过

|

来源于dev.to

转载

array - javascript challenges

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

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

相关专题

更多
js获取数组长度的方法
js获取数组长度的方法

在js中,可以利用array对象的length属性来获取数组长度,该属性可设置或返回数组中元素的数目,只需要使用“array.length”语句即可返回表示数组对象的元素个数的数值,也就是长度值。php中文网还提供JavaScript数组的相关下载、相关课程等内容,供大家免费下载使用。

552

2023.06.20

js刷新当前页面
js刷新当前页面

js刷新当前页面的方法:1、reload方法,该方法强迫浏览器刷新当前页面,语法为“location.reload([bForceGet]) ”;2、replace方法,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL,语法为“location.replace(URL) ”。php中文网为大家带来了js刷新当前页面的相关知识、以及相关文章等内容

374

2023.07.04

js四舍五入
js四舍五入

js四舍五入的方法:1、tofixed方法,可把 Number 四舍五入为指定小数位数的数字;2、round() 方法,可把一个数字舍入为最接近的整数。php中文网为大家带来了js四舍五入的相关知识、以及相关文章等内容

731

2023.07.04

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

477

2023.09.01

JavaScript转义字符
JavaScript转义字符

JavaScript中的转义字符是反斜杠和引号,可以在字符串中表示特殊字符或改变字符的含义。本专题为大家提供转义字符相关的文章、下载、课程内容,供大家免费下载体验。

394

2023.09.04

js生成随机数的方法
js生成随机数的方法

js生成随机数的方法有:1、使用random函数生成0-1之间的随机数;2、使用random函数和特定范围来生成随机整数;3、使用random函数和round函数生成0-99之间的随机整数;4、使用random函数和其他函数生成更复杂的随机数;5、使用random函数和其他函数生成范围内的随机小数;6、使用random函数和其他函数生成范围内的随机整数或小数。

990

2023.09.04

如何启用JavaScript
如何启用JavaScript

JavaScript启用方法有内联脚本、内部脚本、外部脚本和异步加载。详细介绍:1、内联脚本是将JavaScript代码直接嵌入到HTML标签中;2、内部脚本是将JavaScript代码放置在HTML文件的`<script>`标签中;3、外部脚本是将JavaScript代码放置在一个独立的文件;4、外部脚本是将JavaScript代码放置在一个独立的文件。

656

2023.09.12

Js中Symbol类详解
Js中Symbol类详解

javascript中的Symbol数据类型是一种基本数据类型,用于表示独一无二的值。Symbol的特点:1、独一无二,每个Symbol值都是唯一的,不会与其他任何值相等;2、不可变性,Symbol值一旦创建,就不能修改或者重新赋值;3、隐藏性,Symbol值不会被隐式转换为其他类型;4、无法枚举,Symbol值作为对象的属性名时,默认是不可枚举的。

551

2023.09.20

Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

0

2026.01.14

热门下载

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

精品课程

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

共21课时 | 2.6万人学习

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

共8课时 | 1.5万人学习

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

共0课时 | 0人学习

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

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