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)
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.
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.
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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With