59

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

ex: an array with 24 slots that defaults to 0

Esko
  • 29,022
  • 11
  • 55
  • 82
Derek Adair
  • 21,846
  • 31
  • 97
  • 134
  • 4
    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

18 Answers18

98

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
  • 81,358
  • 34
  • 189
  • 227
Aik
  • 3,528
  • 3
  • 19
  • 20
53
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,861
  • 4
  • 29
  • 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
  • 102,654
  • 32
  • 106
  • 127
  • 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
24

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]
S.Saderi
  • 4,755
  • 3
  • 21
  • 23
20

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
  • 524,688
  • 99
  • 697
  • 795
  • 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
14

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
  • 13,336
  • 9
  • 61
  • 96
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
  • 510,854
  • 105
  • 1,084
  • 1,005
2

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
  • 35,312
  • 13
  • 75
  • 106
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,078
  • 3
  • 22
  • 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,627
  • 4
  • 40
  • 64
1

Simplest one:

myArray = new Array(24).fill(0)
Nishant
  • 4,659
  • 2
  • 27
  • 43
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
  • 5,026
  • 1
  • 31
  • 40
0
[].fill.call({ length: 24 }, 0);
Ryan Daniels
  • 301
  • 3
  • 6
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]

0
// 1-D array
// array with length 3 and defaults to null
Array(3).fill(null);
/*
  This will look like
  [null, null, null]
*/

// for, 2-D array
// array with length 3 and default value an array of length 3
Array(3)
  .fill(null)
  .map(() => Array(3).fill(null));

/*
This will look like
[[null, null, null],
[null, null, null],
[null, null, null]]

*/
Abhishek
  • 1
  • 1
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Feb 27 '23 at 15:47
  • 1
    Thanks for the feedback, i will add the explanation and will make sure to always add the explanation whenever i answer. – Abhishek Mar 03 '23 at 12:42
  • thanks @Abhishek, it's just a recommendation that will improve the quality of your answer – borchvm Mar 03 '23 at 12:47
-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
  • 565
  • 6
  • 12