Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add same elements to javascript array n times

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)
like image 523
Deke Avatar asked Aug 13 '18 23:08

Deke


People also ask

How do you add the same element multiple times in an array?

We can use the for loop to run the push method to add an item to an array multiple times. We create the fillArray function that has the value and len parameters. value is the value we want to fill in the array. len is the length of the returned array.

How do you repeat values in an array?

The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

How many times number repeated in array JS?

To check how many times an element appears in an array:Declare a count variable and set its value to 0 . Use the forEach() method to iterate over the array. Check if the current element is equal to the specific value. If the condition is met, increment the count by 1 .

How do you repeat a value in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.


1 Answers

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);
like image 170
CertainPerformance Avatar answered Sep 21 '22 05:09

CertainPerformance