48

Is there a way to assign a default values to arrays in javascript?

ex: an array with 24 slots that defaults to 0

Esko
  • 28,382
  • 11
  • 53
  • 80
Derek Adair
  • 21,351
  • 31
  • 94
  • 133
  • 3
    check out [Array.prototype.fill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) – neaumusic Dec 26 '15 at 06:52

17 Answers17

79

You can use the fill function on an array:

Array(24).fill(0)

Note: fill was only introduced in ECMAScript 2015 (alias "6"), so as of 2017 browser support is still very limited (for example no Internet Explorer).

sleske
  • 77,633
  • 33
  • 182
  • 219
Aik
  • 3,139
  • 2
  • 17
  • 19
52
var a = Array.apply(null, Array(24)).map(function() { return 0 });

// or:
var a = Array.apply(null, Array(5)).map(Boolean).map(Number);
deadrunk
  • 13,307
  • 4
  • 28
  • 29
  • 2
    How is map allowed on the first Array? Something about the way you construct the Array allows map to work, when it normally would not – neaumusic Dec 25 '15 at 06:59
27
Array.prototype.repeat= function(what, L){
 while(L) this[--L]= what;
 return this;
}

var A= [].repeat(0, 24);

alert(A)

kennebec
  • 98,993
  • 30
  • 103
  • 125
  • 4
    What's with the weird (Javascript-wise) naming conventions? (@ the use of capital letters.) – Thomas Eding Jan 11 '10 at 22:07
  • Suppose I want to do this but with an array of objects, how do I do that? var A = [].repeat(new myObject(), 10) just copies the references and do not instantiate a new object every time – Morten Oct 30 '11 at 03:31
  • @Morten `repeat = function(what, count, isFactory) { ... }; [].repeat(function() { return new myObject(); }, 10, true);` – Bart van Heukelom Nov 02 '11 at 19:32
  • 3
    This is late, but I just want to add to anyone reading this in the future: **do not call it `repeat`** as ES6 _will_ implement a `repeat` method, meaning you will overwrite default behaviour, which is discouraged. Good solution though. – somethinghere Aug 27 '15 at 08:20
  • The answer below by deadrunk is better, it doesn't change the array prototype, but does the same thing. – kapad May 17 '16 at 10:11
21

A little wordy, but it works.

var aray = [ 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0 ];
tvanfosson
  • 509,016
  • 97
  • 693
  • 791
  • 3
    @KnickerKicker - no, for a one-off 24 element array, I'd probably do exactly this. If it were a large number of items or I needed it repeatedly, then I'd be more clever about it. – tvanfosson Jul 18 '11 at 20:57
  • 4
    Actually, this doesn't answer the question "Is there a way to assign a default values to arrays in javascript?" What this answer does address is the clarifying example. – knight Sep 24 '14 at 15:52
  • 3
    by far the most efficient and clean way to create an array with 24 zeros. – taseenb Feb 04 '16 at 10:14
18

the best and easiest solution is :

Array(length of the array).fill(a default value you want to put in the array)

example

Array(5).fill(1)

and result will be

[1,1,1,1,1]

you can put any thing you like in it:

Array(5).fill({name : ""})

Now if you want to change some of the current value in the array you can use

[the created array ].fill(a new value , start position, end position(not included) )

like

[1,1,1,1,1].fill("a",1,3)

and output is

[1, "a", "a", 1, 1]
Sajad Saderi
  • 3,409
  • 3
  • 17
  • 21
15

If you use a "very modern" browser (check the compatibility table), you can rely on fill:

var array = new Array(LENGTH);
array.fill(DEFAULT_VALUE);

For several reasons, the use of new Array() is not appreciated by a lot of developers; so you can do the same as follows:

var array = [];
for(var i=0; i<LENGTH; ++i) array.push(DEFAULT_VALUE);

The latter is much more compatible, and as you can see both solutions are represented by two lines of code.

Vito Gentile
  • 12,019
  • 9
  • 58
  • 89
3

I personally use:

function replicate (n, x) {
  var xs = [];
  for (var i = 0; i < n; ++i) {
    xs.push (x);
  }
  return xs;
}

Example:

var hellos = replicate (100, "hello");
Thomas Eding
  • 33,388
  • 12
  • 68
  • 104
3

If you are using ES6 and up you can use

new Array(24).fill(0);

this also works:

Array.from({ length: 24}, () => 0)
2

No.

You have to use a loop.

var a = new Array(24);
for (var i = a.length-1; i >= 0; -- i) a[i] = 0;
kennytm
  • 491,404
  • 99
  • 1,053
  • 989
1

And now, more cleverly :)
@see JavaScript Array reference
Example on JSFiddle

var len = 100;
var ch = '0';
alert ( new Array(len).join( ch ) );
Tomáš
  • 2,048
  • 3
  • 21
  • 21
  • 1
    Here's a version that gives you numbers as requested in the question: `Array(24).join().split('').map(function(){return 0})` – JussiR Jun 11 '14 at 11:05
1

Use Lodash (https://lodash.com/docs), a robust library for array manipulation which is available for browser too.

var _ = require('lodash');
var A = _.fill(Array(24), 0);
Aman Gupta
  • 3,229
  • 4
  • 32
  • 59
1

Another way to achieve the same -

Array.from(Array(24),()=>5)

Array.from accepts a second param as its map function.

Sunny R Gupta
  • 4,858
  • 1
  • 31
  • 40
0
[].fill.call({ length: 24 }, 0);
Ryan Daniels
  • 301
  • 3
  • 6
0

Simplest one:

myArray = new Array(24).fill(0)
Nishant
  • 4,199
  • 2
  • 24
  • 42
0

Syntax which i am using below is based on ECMA Script 6/es6

let arr=[];

arr.length=5; //Size of your array;

[...arr].map(Boolean).map(Number); //three dot operator is called spread Operator introduce in ECMA Script 6

------------Another way-------------

let variable_name=new Array(size).fill(initial_value)

for ex- let arr=new Array(5).fill(0) //fill method is also introduced in es6

Another way as per ECMA 5 or es5

var variable_name=Array.apply(null,Array(size)).map(Boolean).map(Number)

var arr=Array.apply(null,Array(5)).map(Boolean).map(Number);

All of them will give you same result : [0,0,0,0,0]

-3
(new Array(5).toString().replace(/,/g, "0,") + "0").split(",")

// ["0", "0", "0", "0", "0"]
serious
  • 271
  • 2
  • 7
  • 4
    I have no idea why this was ever upvoted. He asked for an array full of 0s not the string version of 0. plus this code is horribly written, why use a regex replace when you can just do `var a = new Array(6).join(0).split('')`? – Russ Bradberry May 07 '12 at 19:22
-6

If you want BigO(1) instead of BigO(n) please check below solution:

Default value of an array is undefined. So if you want to set default to 0, you have to loop all elements of array to set them to 0.

If you have to do that, it's ok. But I think it'll better if you check the value when want to get value of the element.

Define a function 'get': to get value of the array. myArray[index], if myArray[index] undefined, return '0', else return the value.

const get = (arr, index) => {
  return arr[index] === undefined ? 0 : arr[index];
}

Use:

const myArray = ['a', 'b', 1, 4];
get(myArray, 2); // --> 'b' 
get(myArray, 102344); // --> 0;
SLyHuy
  • 381
  • 3
  • 9