Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of zeros in typescript?

Currently, I'm using Array.apply(null, new Array(10)).map(Number.prototype.valueOf, 0); to create an array of 0.

I'm wondering is there a better (cleaner) way to do this in typescript?

like image 799
David Liu Avatar asked Apr 22 '15 00:04

David Liu


People also ask

How do you create an array of zeros?

Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.

How do I create an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you define a type of array in TypeScript?

In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.

How do you create an array of zeros in Java?

for other values use Arrays utility class. int arrayDefaultedToTen[] = new int[100]; Arrays. fill(arrayDefaultedToTen, 10); this method fills the array (first arg) with 10 (second arg).


4 Answers

You can add to the open Array<T> interface to make the fill method available. There is a polyfill for Array.prototype.fill on MDN if you want older browser support.

interface Array<T> {
    fill(value: T): Array<T>;
}

var arr = Array<number>(10).fill(0);

View on Playground

Eventually the fill method will find its way into the lib.d.ts file and you can delete your one (the compiler will warn you when you need to do this).

like image 151
Fenton Avatar answered Oct 07 '22 09:10

Fenton


As of now you can just do

const a = new Array<number>(1000).fill(0);

Make sure you include <number> otherwise it will infer a's type as any[].

like image 38
Timmmm Avatar answered Oct 07 '22 10:10

Timmmm


Having reviewed the concept of array holes I would do:

Array.apply(null, new Array(10)).map(()=> 0);

Not a big saving but is some.

like image 4
basarat Avatar answered Oct 07 '22 09:10

basarat


You could pass and integer argument to the Array constructor, this will return a new JavaScript array with its length property set to that number, plus you can use .fill to fills all the elements of an array from index zero.

const data = ([...Array(10).fill(0)])
console.log(data)
like image 4
GibboK Avatar answered Oct 07 '22 10:10

GibboK