简体   繁体   English

在 JavaScript 中从一维数组创建二维数组

[英]Creating a 2D array from a 1D array in JavaScript

I have the following array:我有以下数组:

let numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20];

I create a new array without the duplicate values:我创建了一个没有重复值的新数组:

let counter = [...new Set(array)]; 
//Output: [ 10, 20, 30, 50 ]

I want to instantiate the counter array as a 2D/nested array so that it looks like this:我想将计数器数组实例化为 2D/嵌套数组,使其看起来像这样:

//counter output: [[10,4][20, 3][30, 1][50,1]]

What's the best way to do this?做到这一点的最佳方法是什么? The numbers array could have various elements and therefore the number of elements in the counter array could vary.数字数组可能有各种元素,因此计数器数组中的元素数量可能会有所不同。

This answer is for the original question (how to create an array of [[10, 0],[20, 0],[30, 0],[50, 0]] from the Set):此答案适用于原始问题(如何从 Set 创建[[10, 0],[20, 0],[30, 0],[50, 0]]数组):

Instead of spreading the Set, use Array.from() to create an array of pairs:使用Array.from()创建一个数组对,而不是传播 Set:

 const numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20]; const counter = Array.from(new Set(numbers), v => [v, 0]); console.log(counter);

Assuming you actually want that second sub-array index to represent the number of occurrences of each number ( ed: confirmed now ), you can collect the counts into a Map and then convert that to an array假设您实际上希望第二个子数组索引表示每个数字的出现次数( ed:confirmed now ),您可以将计数收集到Map ,然后将其转换为数组

 let numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20]; const counter = [...numbers.reduce((map, n) => map.set(n, (map.get(n) ?? 0) + 1), new Map())] console.info(JSON.stringify(counter)) // stringifying so it's all on one line

The array conversion works since Map supports the common entries format of数组转换有效,因为Map支持常见的条目格式

[ [ key, value ], [ key, value ], ... ]

and using spread syntax implicitly converts it to an entries array.并使用扩展语法将其隐式转换为条目数组。

一种方法是采用您已经使用过的想法并映射这些值,返回带有该值和附加零的新数组。

let numbers = [...new Set([10, 20, 20, 10, 10, 30, 50, 10, 20])].map(value=>[value,0]);

You can convert your original array into an object (hash map) to keep track of the count.您可以将原始数组转换为对象(哈希图)以跟踪计数。 And then convert it into to Object.entries() array.然后将其转换为Object.entries()数组。

 const numbers = [10, 20, 20, 10, 10, 30, 50, 10, 20]; let obj = {}; numbers.forEach(n => { obj[n] = obj[n] || 0; obj[n]++; }); const counter = Object.entries(obj).map(e => [+e[0], e[1]]); console.log(counter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM