Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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()
about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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: []}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!