Is it possible to .push() a value to an array but replicate the pushed value n times without using a traditional loop to perform the replication? For instance using .fill(). The examples I have seen declare a new Array() with a length of n, and .fill() it with a value. However, I have not seen any examples dealing with .push(), so I'm not even sure it is possible.
Example of what I'm looking for:
var my_array = [];
for (var i = 0; i < 5; i++) {
my_array.push(5);
};
Scenario:
I'm pulling values from three different arrays or objects to populate a single matrix that will be ran through a Munkres (Hungarian) algorithm, in order to avoid introducing another loop I would like to .push values to the matrix and use .fill() to repeat the value n times.
Example:
var s = […];
var a = […];
var p = […];
var matrix = [];
for (var i = 0; i < s.length; i++) {
var preferences = [];
for (var j = 0; j < p.length; j++ {
var pid = p[j];
for (var k = 0; k < a.length; k++ {
if (pid == a[k]) {
for (var l = 0; l < 5; l++) { // <-- THIS.
preferences.push(a[k]);
};
};
};
};
matrix.push(preferences);
};
Is it possible to .push() a value to an array but replicate the pushed value n times without using a traditional loop to perform the replication? For instance using .fill(). The examples I have seen declare a new Array() with a length of n, and .fill() it with a value. However, I have not seen any examples dealing with .push(), so I'm not even sure it is possible.
Example of what I'm looking for:
var my_array = [];
for (var i = 0; i < 5; i++) {
my_array.push(5);
};
Scenario:
I'm pulling values from three different arrays or objects to populate a single matrix that will be ran through a Munkres (Hungarian) algorithm, in order to avoid introducing another loop I would like to .push values to the matrix and use .fill() to repeat the value n times.
Example:
var s = […];
var a = […];
var p = […];
var matrix = [];
for (var i = 0; i < s.length; i++) {
var preferences = [];
for (var j = 0; j < p.length; j++ {
var pid = p[j];
for (var k = 0; k < a.length; k++ {
if (pid == a[k]) {
for (var l = 0; l < 5; l++) { // <-- THIS.
preferences.push(a[k]);
};
};
};
};
matrix.push(preferences);
};
javascript
arrays
Share
edited Mar 25, 2019 at 23:08artomason
asked Mar 25, 2019 at 23:04
artomasonartomason4,03366 gold badges2828 silver badges4545 bronze badges2
I think you need to use fill, but without push - push returns the new length of the array.
– Jack Bashford
CommentedMar 25, 2019 at 23:08
The problem is I need to append the values to the preferences array so they are retained each iteration. I think if I create an array with the desired values and .push() that to the preferences array it would result in [[ ],[ ],[ ]]
– artomason
CommentedMar 25, 2019 at 23:09