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);
};
You could use concat and fill:
preferences = preferences.concat(Array(5).fill(a[k]));
Related
I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)
var A=[[],[]];
for(var i=0;i<12;i++){
for(var j=0;j<81;j++){
A[i][j]='q';
}
}
It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.
All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.
This does the job in one line.
var A = Array(12).fill(null).map(()=>Array(81).fill('q'))
This is an array of references and a bad idea as harunurhan commented.
var A = Array(12).fill(Array(81).fill('q'));
The Array.from() method creates a new, shallow-copied Array instance
from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
var A=[[], []];
^ This line declares a two dimensional array of size 1x2. Try this instead:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
Since fill() is the most succinct and intuitive, and it works as intended for immutable values, my preference would be an outer from() and an inner fill():
Array.from({length: 12}, _ => new Array(81).fill('q'));
The best approach to fill up 2D array would be like the following
let array2D = [], row = 3, col = 3, fillValue = 1
for (let i = 0; i < row; i++){
let temp = []
for (let j = 0; j < col; j++){
temp[j] = fillValue
}
array2D.push(temp)
}
You need to initialise a new array for i each time the first loop runs, and you don't need to set the layout of the array before you create it (Remove the [], [] inside the declaration of A). Try this:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
console.log(A);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)
var A=[[],[]];
for(var i=0;i<12;i++){
for(var j=0;j<81;j++){
A[i][j]='q';
}
}
It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.
All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.
This does the job in one line.
var A = Array(12).fill(null).map(()=>Array(81).fill('q'))
This is an array of references and a bad idea as harunurhan commented.
var A = Array(12).fill(Array(81).fill('q'));
The Array.from() method creates a new, shallow-copied Array instance
from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
var A=[[], []];
^ This line declares a two dimensional array of size 1x2. Try this instead:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
Since fill() is the most succinct and intuitive, and it works as intended for immutable values, my preference would be an outer from() and an inner fill():
Array.from({length: 12}, _ => new Array(81).fill('q'));
The best approach to fill up 2D array would be like the following
let array2D = [], row = 3, col = 3, fillValue = 1
for (let i = 0; i < row; i++){
let temp = []
for (let j = 0; j < col; j++){
temp[j] = fillValue
}
array2D.push(temp)
}
You need to initialise a new array for i each time the first loop runs, and you don't need to set the layout of the array before you create it (Remove the [], [] inside the declaration of A). Try this:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
console.log(A);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
I am having some random JSON data at the moment, therefore I cannot using standrad way to do it, cannot do it one by one.
For example if i am going to store specific data as array i will do something like below
var tester = []; // store their names within a local array
for(var k = 0; i < data.result.length; i++){ //maybe 6
for(var i = 0; i < data.result.data.length; i++){ //maybe 30 times in total
tester.push(data.result[k].data[i].someNames);
}
}
But since I cannot predict how many set of data i have i can't really do something like
var tester = [];
var tester2 = [];
var tester3 = [];
var tester4 = [];
for(var i = 0; i < data.result.data.length; i++){ //maybe 30 times in total
tester.push(data.result[0].data[i].someNames);
tester2.push(data.result[1].data[i].someNames);
tester3.push(data.result[2].data[i].someNames);
tester4.push(data.result[3].data[i].someNames);
}
if there' any better way which using for loop to store these data?
Make tester a 2-dimensional array and use nested loops.
var tester = [];
for (var i = 0; i < data.result.length; i++) {
var curTester = [];
var result = data.result[i];
for (var j = 0; j < result.data.length; j++) {
curTester.push(result.data[j].someNames);
}
tester.push(curTester);
}
Some general principles:
Any time you find yourself defining variables with numeric suffixes, they should probably be an array.
When you don't know how many of something you're going to have, put them in an array.
I need to check from a string, if a given fruit has the correct amount at a given date. I am turning the string into a 2d array and iterating over the columns.This code works, but I want to know : is there a better way to do it? I feel like this could be done avoiding 4 for loops.
function verifyFruit(name, date, currentValue) {...}
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var rows = data.split('\n');
var colCount = rows[0].split(',').length;
var arr = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < colCount; j++) {
var temp = rows[i].split(',');
if (!arr[i]) arr[i] = []
arr[i][j] = temp[j];
}
}
for (var i = 1; i < colCount; i++) {
for (var j = 1; j < rows.length; j++) {
verifyFruit(arr[0][i], arr[j][0], arr[j][i]);
}
}
This would be a good candidate for Array.prototype.map
var data = "Date,Apple,Pear\n2015/04/05,2,3\n2015/04/06,8,6"
var parsedData = data.split("\n").map(function(row){return row.split(",");})
What map does is iterate over an array and applies a projection function on each element returning a new array as the result.
You can visualize what is happening like this:
function projection(csv){ return csv.split(",");}
var mappedArray = [projection("Date,Apple,Pear"),projection("2015/04/05,2,3"),projection("2015/04/06,8,6")];
The following code will generate 10 arrays, each with 10 subarrays, each with 10 subarrays, each with 10 subarrays.
paths = [];
for (var i = 0, len_i = 10; i < len_i; ++i) { // 1st dimension
paths.push([]);
for (var j = 0, len_j = 10; j < len_j; ++j) { // 2nd dimension
paths[i].push([]);
for (var k = 0, len_k = 10; k < len_k; ++k) { // 3rd dimension
paths[i][j].push([]);
for (var l = 0, len_l = 10; l < len_l; ++l) { // 4th dimension
paths[i][j][k].push([]);
paths[i][j][k][l] = [];
}
}
}
}
I will eventually need to do this with more dimensions and am curious to know if any ingenious developers out there can accomplish this with a function of the form:
function makePaths(quantityInEachArray, dimensions) {
paths = [];
quantityInEachArray = (typeof quantityInEachArray === "undefined") ? 10 : quantityInEachArray;
dimensions = (typeof dimensions === "undefined") ? 4 : dimensions;
// Do some magic
return paths;
}
That function, in its default form, would return the same thing as the for loops I demonstrated above.
I understand that this is not a standard practice but I am doing it for a very specific reason and need to test the performance of it.
How do I modify this code to produce nth dimensional arrays?
You can use recursive function:
function nthArray(n, l) {
if(n < 1) return;
var arr = new Array(l);
for(var i=0; i<l; ++i)
arr[i] = nthArray(n-1, l);
return arr;
}
A simple magic would be (without recursion):
paths = []
arrays = [paths]
for (var i = 0; i < dimensions; i++) {
tmpArr = []
for (var k = 0; k < arrays.length; k++) {
for (var j = 0; j < size; j++) {
val = []
tmpArr.push(val)
arrays[k].push(val)
}
}
arrays = tmpArr
}
(I am not very fluent in javascript, you probably need to declare vars at the beginning and every thing, but that's the idea)