jenesaisquoi
jenesaisquoi

Reputation: 65

initializing a javascript dictionary with empty arrays

I want to initialize a dictionary with k empty arrays (keys are integers from 0 to k-1), something similar to python comprehension list:

data = {k: [] for k in range(2)}

Is something possible in javascript? if not, what would be the best way to do it?

Upvotes: 2

Views: 1678

Answers (3)

masadamsahid
masadamsahid

Reputation: 510

Yes, its possible to do that in just a single line in JS.

let data = {
  ...Array.from({ length: 2 }, () => [])
};

console.log(data);

You can also experiment it, here


Make a function of it.

It will be easier and reusable if you make a function of it. Here the example:

// traditional function
function generateData(howMany) {
  return {
    ...Array.from({ length: howMany }, () => [])
  };
}

// ES 6 function
const generateDataES6 = (howMany) => ({ ...Array.from({ length: howMany }, () => []) });

console.log("traditionnal:", generateData(4));
console.log("ES6:", generateDataES6(3));

Results:

enter image description here


References:

  1. Spread operator: MDN - Spread Syntax
  2. Array.from() : MDN - Array.from() and W3-School - JS Array.from()

Upvotes: 2

novalagung
novalagung

Reputation: 11532

I believe your phyton statement will generate the output below

data = {k: [] for k in range(2)}

print(data)
// {0: [], 1: []}

In javascript, you can utilize .reduce() to achieve the same result.

data = [...Array(2).keys()].reduce((obj, d) => { obj[d] = []; return obj; }, {})

console.log(data)
// {0: [], 1: []}

Upvotes: 0

AlexSp3
AlexSp3

Reputation: 2293

In python

>>> {k: [] for k in range(2)}
{0: [], 1: []}

In javascript, you should do the following:

const data = {};
for (let k = 0; k < 2; ++k) data[k] = [];

console.log(data)

Upvotes: 0

Related Questions