44

Code

var cool = new Array(3);
cool[setAll] = 42; //cool[setAll] is just a pseudo selector..
alert(cool);

Result

A alert message:

42,42,42

How do I change/set all values of an array to a specific value?

9 Answers 9

60

There's no built-in way, you'll have to loop over all of them:

function setAll(a, v) {
    var i, n = a.length;
    for (i = 0; i < n; ++i) {
        a[i] = v;
    }
}

http://jsfiddle.net/alnitak/xG88A/

If you really want, do this:

Array.prototype.setAll = function(v) {
    var i, n = this.length;
    for (i = 0; i < n; ++i) {
        this[i] = v;
    }
};

and then you could actually do cool.setAll(42) (see http://jsfiddle.net/alnitak/ee3hb/).

Some people frown upon extending the prototype of built-in types, though.

EDIT ES5 introduced a way to safely extend both Object.prototype and Array.prototype without breaking for ... in ... enumeration:

Object.defineProperty(Array.prototype, 'setAll', {
    value: function(v) {
        ...
    }
});

EDIT 2 In ES6 draft there's also now Array.prototype.fill, usage cool.fill(42)

Sign up to request clarification or add additional context in comments.

4 Comments

I feel obliged to add a caveat here: extending native objects (in this case Array) is considered bad practice by most.
@Steve which is exactly what I say in the last line. However ES5 provides a safe way to do it using Object.createProperty(Array.prototype, 'setAll', ...)
Whoops my bad. TLDR is getting shorter and shorter these days :)
thanks for the fill tip. Fill is a lot of fun. I ended up using clones of manually created arrays (var1 = [...ArrayOfTrue]; var2 = [...ArrayOfFalse] is quicker in my case then var1.fill(true) but it'll be usefull down the line I'm sure.
48

The ES6 approach is very clean. So first you initialize an array of x length, and then call the fill method on it.

let arr = new Array(3).fill(9)

this will create an array with 3 elements like:

[9, 9, 9]

5 Comments

Sadly there is very little browser support for the .fill() method as of 2016. However, I found this very useful for use with TypeScript.
@MarcoDelValle it's not a problem with a polyfill
@Marquizzo There should be better support here in 2019
Yes, it's improved substantially in the last 3 years. It looks like as of today, only IE does not support it
This should be the best answer in 2019
29

map is the most logical solution for this problem.

let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]

However, if there is a chance that the array is sparse, you'll need to use for or, even better, for .. of.

See:

7 Comments

poor answer - not only is this is a misuse of Array.prototype.map (you should use forEach to iterate over an array, and .map only if you wish to return a new array based on it) but also requires that the array already have values in it. Both .map and .forEach will ignore array elements that have undefined keys.
@Alnitak See the second code example for point #1, and don't see why point #2 makes this a poor answer. Does this approach "Set all values of an array"? Yes.
@mustafa.0x no, it doesn't "set all values of an array". JS arrays can be sparse, i.e. there can be elements between 0 and length - 1 that have no defined value. .map will ignore those elements, leaving the array unfilled. The second .map version fails the OP requirement in that it returns a new array, and does not mutate the original.
@Alnitak I can change the second example to xs = xs.map() if that's important to you =)
No, my point is that .map is entirely the wrong tool for the job not just because of its array return semantics but also because of the sparse element skipping.
|
4

It's 2019 and you should be using this:

let arr = [...Array(20)].fill(10)

So basically 20 is the length or a new instantiated Array.

Comments

3

Use a for loop and set each one in turn.

Comments

3

Actually, you can use this perfect approach:

let arr = Array.apply(null, Array(5)).map(() => 0);
// [0, 0, 0, 0, 0]

This code will create array and fill it with zeroes. Or just:

let arr = new Array(5).fill(0)

Comments

1

The other answers are Ok, but a while loop seems more appropriate:

function setAll(array, value) {
  var i = array.length;
  while (i--) {
    array[i] = value;
  }
}

A more creative version:

function replaceAll(array, value) {
  var re = new RegExp(value, 'g');
  return new Array(++array.length).toString().replace(/,/g, value).match(re);
}

May not work everywhere though. :-)

1 Comment

good choice for the reverse array loop, we need more of those in js land
0

Found this while working with Epicycles - clearly works - where 'p' is invisible to my eyes.

/** Convert a set of picture points to a set of Cartesian coordinates */
function toCartesian(points, scale) {
  const x_max = Math.max(...points.map(p=>p[0])),
  y_max = Math.max(...points.map(p=>p[1])),
  x_min = Math.min(...points.map(p=>p[0])),
  y_min = Math.min(...points.map(p=>p[1])),
  signed_x_max = Math.floor((x_max - x_min + 1) / 2),
  signed_y_max = Math.floor((y_max - y_min + 1) / 2);

  return points.map(p=>
  [ -scale * (signed_x_max - p[0] + x_min),
  scale * (signed_y_max - p[1] + y_min) ] );
}

Comments

0

You can use an empty statement.

const arr = [1, 2 ,3];
for (let i = 0; i < arr.length; arr[i++] = 42);
console.log(arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.