default array values
Asked Answered
S

18

61

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

ex: an array with 24 slots that defaults to 0

Shiv answered 11/1, 2010 at 20:41 Comment(1)
check out Array.prototype.fillTaconite
E
26
Array.prototype.repeat= function(what, L){
 while(L) this[--L]= what;
 return this;
}

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

alert(A)

Element answered 11/1, 2010 at 21:14 Comment(5)
What's with the weird (Javascript-wise) naming conventions? (@ the use of capital letters.)Chally
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 timeShiism
@Shiism repeat = function(what, count, isFactory) { ... }; [].repeat(function() { return new myObject(); }, 10, true);Ventris
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.Beberg
The answer below by deadrunk is better, it doesn't change the array prototype, but does the same thing.Galactic
B
107

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).

Bilski answered 31/10, 2016 at 17:11 Comment(0)
I
53
var a = Array.apply(null, Array(24)).map(function() { return 0 });

// or:
var a = Array.apply(null, Array(5)).map(Boolean).map(Number);
Influence answered 10/10, 2013 at 4:1 Comment(1)
How is map allowed on the first Array? Something about the way you construct the Array allows map to work, when it normally would notTaconite
E
26
Array.prototype.repeat= function(what, L){
 while(L) this[--L]= what;
 return this;
}

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

alert(A)

Element answered 11/1, 2010 at 21:14 Comment(5)
What's with the weird (Javascript-wise) naming conventions? (@ the use of capital letters.)Chally
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 timeShiism
@Shiism repeat = function(what, count, isFactory) { ... }; [].repeat(function() { return new myObject(); }, 10, true);Ventris
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.Beberg
The answer below by deadrunk is better, it doesn't change the array prototype, but does the same thing.Galactic
G
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]
Godfrey answered 12/8, 2019 at 18:55 Comment(0)
P
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 ];
Phenacaine answered 11/1, 2010 at 20:47 Comment(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.Phenacaine
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.Amarillas
by far the most efficient and clean way to create an array with 24 zeros.Lawana
T
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.

Tense answered 25/6, 2015 at 14:27 Comment(0)
F
3

If you are using ES6 and up you can use

new Array(24).fill(0);

this also works:

Array.from({ length: 24}, () => 0)
Fillin answered 29/7, 2018 at 13:52 Comment(0)
S
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;
Spitter answered 11/1, 2010 at 20:44 Comment(1)
Technically it's still a loop, moved into a function.Spitter
C
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");
Chally answered 11/1, 2010 at 22:4 Comment(0)
S
1

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

var len = 100;
var ch = '0';
alert ( new Array(len).join( ch ) );
Sobriety answered 1/5, 2014 at 6:0 Comment(1)
Here's a version that gives you numbers as requested in the question: Array(24).join().split('').map(function(){return 0})Pediment
S
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);
Suellensuelo answered 13/10, 2015 at 7:12 Comment(0)
A
1

Simplest one:

myArray = new Array(24).fill(0)
Ablebodied answered 20/4, 2017 at 14:15 Comment(1)
Your answer is redundant.Usurious
M
1

Another way to achieve the same -

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

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

Mckissick answered 17/1, 2019 at 17:59 Comment(0)
H
0
[].fill.call({ length: 24 }, 0);
Hemispheroid answered 16/7, 2016 at 22:31 Comment(0)
O
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]

Option answered 30/8, 2018 at 14:41 Comment(0)
P
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]]

*/
Pixilated answered 20/2, 2023 at 16:1 Comment(3)
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.Danseuse
Thanks for the feedback, i will add the explanation and will make sure to always add the explanation whenever i answer.Pixilated
thanks @Abhishek, it's just a recommendation that will improve the quality of your answerDanseuse
G
-3
(new Array(5).toString().replace(/,/g, "0,") + "0").split(",")

// ["0", "0", "0", "0", "0"]
Genevivegenevra answered 20/8, 2010 at 15:16 Comment(1)
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('')?Epictetus
V
-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;
Vazquez answered 30/12, 2011 at 4:20 Comment(2)
function get (i) { return 0; }Chally
Big-O of my solution is O(1) Another ways alway have O(n)Vazquez

© 2022 - 2024 — McMap. All rights reserved.