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);
};
Share
edited Mar 25, 2019 at 23:08
artomason
asked Mar 25, 2019 at 23:04
artomasonartomason
4,0336 gold badges28 silver badges45 bronze badges
2
-
I think you need to use
fill
, but withoutpush
-push
returns the new length of the array. – Jack Bashford Commented Mar 25, 2019 at 23:08 -
The problem is I need to
append
the values to thepreferences
array so they are retained each iteration. I think if I create an array with the desired values and.push()
that to thepreferences
array it would result in[[ ],[ ],[ ]]
– artomason Commented Mar 25, 2019 at 23:09
1 Answer
Reset to default 8You could use concat
and fill
:
preferences = preferences.concat(Array(5).fill(a[k]));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745069890a4609481.html
评论列表(0条)