skip to Main Content

If the property to be calculated only requires one statement, it is pretty simple

let object = {
    array: new Array(10)
};

Alternatively I can also do the following (though I don’t like it as much)

let object = {};
object.array = new Array(10);

But what if I want to (e.g.) initialize the array with values of 0 (by deafult the values are "undefined")? I can only do it the second way

let object = {};
object.array = new Array(10);
for(let element of array){
    element = 0;
}

The closest thing to the first method that comes to mind might be doing something like this

let object = {
    array: (function(){
        let array = new Array(10);
        for(let element of array){
            element = 0;
        }
        return array;
    })()
}

Maybe there is a simpler way to do this that I do not know of?

Edit: The array was just the first thing that came to mind when thinking of an example. My problem does not lie exclusively on initializing an array, I am looking for a more general solution than using Array.fill().

4

Answers


  1. Just use Array.fill:

    let object = {
      array: Array(10).fill(0)
    }
    console.log(object)

    Or, to do a slightly more complex array initialization:

    let object = {
      array: Array(10).fill().map((_,i) => `hello ${i}`)
    }
    console.log(object)

    To initialize an array of length 10, with the number 1, except in indices 4 and 7:

    let object = {
      array: Array(10).fill(1).map((e,i) => [4, 7].includes(i) ? 0 : e)
    }
    console.log(object)

    You can also use arrow functions and comma expressions (but it can easily start to become unreadable). Note that the arrow function declares parameters that it can use as variables, instead of having to do let x = , which would require braces.

    let object = {
      array: (x => (x = new Array(10).fill(), x.forEach((e,i) => x[i] = Math.random()), x))()
    }
    console.log(object)

    I recommend that instead of doing complex one-liners, you create your own separate helper functions. This will maximise code readability. For example, you could create a helper function called function createArrayWithRandomValues(length, upperBound).

    Login or Signup to reply.
  2. You can use fill to fill array with 0 as:

    The fill() method of Array instances changes all elements within a range of indices in an array to a static value. It returns the modified array.

    let object = {
      array: Array(10).fill(0)
    };
    
    console.log(object);

    Also, you can use Array.from as:

    The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

    let object = {
        array: Array.from({ length: 10 }).fill(0)
    };
    
    console.log(object);
    Login or Signup to reply.
  3. There are lots of ways to initialize an array. Here are some examples based on your requirements:

    1. Using Array.fill

    This is useful if your array consists a single value

    let object = {
      array: Array(10).fill(0)
    }
    console.log(object);
    1. Using Array.from

    This is useful if want your array elements based on their original value or indices.

    let object = {
      array: Array.from({ length: 10 }, (element, i) => i)
    }
    console.log(object);
    1. Using generators

    This is useful if you want to dynamically control how your array is formed.

    let object = {
      array: [...function*() {
        yield 'T-MINUS';
        for (let i = 10; i > 0; i--) {
          yield i;
          
          if (i === 7) {
            yield '7 is my favorite number btw'
          }
        }
        yield 'LAUNCH';
      }()]
    }
    console.log(object);

    1. Using Array.with

    This is useful for "I don’t want to change the entire array to 0, but only the value of the 4th and 7th element"

    let object = {
      array: new Array(10).with(3, 0).with(6, 0)
    }
    
    console.log(object);
    Login or Signup to reply.
  4. You can use an IIFE to perform more complex inline calculation of property values from within an object initializer. As an example based on the posted code:

    const obj = {
        array: (()=> { // example code
            const a = new Array(10);
            return a.fill(0);
         })(),
        hw: "hello world",
    }
    
    console.log(obj.hw, obj.array); 
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search