23
var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");

Instead of pushing same elements how can write it once like this:

fruits.push("lemon" * 4 times)
3

4 Answers 4

44

For primitives, use .fill:

var fruits = new Array(4).fill('Lemon');
console.log(fruits);

For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array.

const fruits = new Array(4).fill({ Lemon: 'Lemon' });

fruits[0].Apple = 'Apple';
console.log(JSON.stringify(fruits));


// The above doesn't work for the same reason that the below doesn't work:
// there's only a single object in memory

const obj = { Lemon: 'Lemon' };

const fruits2 = [];
fruits2.push(obj);
fruits2.push(obj);
fruits2.push(obj);
fruits2.push(obj);

fruits2[0].Apple = 'Apple';
console.log(JSON.stringify(fruits2));

Instead, explicitly create the object on each iteration, which can be done with Array.from:

var fruits = Array.from(
  { length: 4 },
  () => ({ Lemon: 'Lemon' })
);
console.log(fruits);

For an example of how to create a 2D array this way:

var fruits = Array.from(
  { length: 2 }, // outer array length
  () => Array.from(
    { length: 3 }, // inner array length
    () => ({ Lemon: 'Lemon' })
  )
);
console.log(fruits);

3
3

Try using Array constructor:

let myArray = Array(times).fill(elemnt)

See more here Array

1
  • 2
    You don't need new for arrays.
    – Barmar
    Aug 14, 2018 at 1:06
2

You shouldn't use the array constructor, use [] instead.

const myArray = [];   // declare array

myArray.length = 5; // set array size
myArray.fill('foo'); // fill array with any value

console.log(myArray); // log it to the console

1
   const item = 'lemon'
   const arr = Array.from({length: 10}, () => item)

const item = 'lemon'
const arr = Array.from({length: 10}, () => item)
console.log('arr', arr)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.