Mr.Helpme
Mr.Helpme

Reputation: 51

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:

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

Upvotes: 1

Views: 226

Answers (4)

Ori Drori
Ori Drori

Reputation: 191936

This answer is for the original question (how to create an array of [[10, 0],[20, 0],[30, 0],[50, 0]] from the Set):

Instead of spreading the Set, use Array.from() to create an array of pairs:

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

const counter = Array.from(new Set(numbers), v => [v, 0]);

console.log(counter);

Upvotes: 3

Rahul Bhobe
Rahul Bhobe

Reputation: 4451

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.

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

Upvotes: 0

Phil
Phil

Reputation: 164729

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

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

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

and using spread syntax implicitly converts it to an entries array.

Upvotes: 2

Eli Spiegel
Eli Spiegel

Reputation: 39

One way is take the ideas you have already used and map across those values returning new arrays with the value and an additional zero.

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

Upvotes: 0

Related Questions