Remove empty row from array in javascript - javascript

I am trying to check and remove any empty row in my table mapped to an array in javascript.
Sample array would be like below.
1 2 3
4 5 6
7 8 9
Now this array is having 4 rows and 3rd one is empty which I want to remove. How to do that. I tried using if(adata[i]) is not null, but that wont work since an indivdual value can be null. i want to check for complete row being null

This short code should match your requirement :
var input = [[1,,3], [11,, ,12], [,,,,,], [37,38,39]];
var result = input.filter(element => element.join("") != "");
console.log(result); // [ [ 1, , 3 ], [ 11, , , 12 ], [ 37, 38, 39 ] ]
Edit : for ES5 you'll write rather
var result = input.filter(function(element) {return element.join("") != ""});

Related

how to keep track of objects inserted in an array

When clicking add it should keep inserting object to the array and the order Id should be based from the current order id + 1 of the objects on the array so for example if if templatesDto is empty then every order in the object should increment starting from 0 when I click add
but for example there are existing data on the templatesDto
example
[
{
"id": 255,
"order": 0,
},
{
"id": 256,
"order": 1,
},
{
"id": 256,
"order": 2,
},
]
then if I click add the next order value of the new added object should be 3 since the last one is 2.
Any idea guys ? Thank you.
#html code
<button (click)="add()" mat-stroked-button mat-button class="btn-add-entitlement action-btn">
<mat-icon aria-label="Add" class="add-icon">add</mat-icon> Add
</button>
#ts code - to insert object to array
this.templatesDto= []
add() {
this.templatesDto.push({
id: 0,
order : 0,
})
}
#sample result if I click add and there are no data in templatesDto
[
{
"id": 0,
"order": 0,
},
{
"id": 0,
"order": 1,
},
{
"id": 0,
"order": 2,
}
....
]
Set order to call getNextOrder() with the function being:
function getNextOrder() {
if (this.templatesDto.length === 0) {
return 0
}
let maxOrder = 0
for (const template of this.templatesDto) {
if (template.order > maxOrder) {
maxOrder = template.order
}
}
return maxOrder + 1
}
This function goes through all objects in the array, gets the highest order value and then returns it incremented by 1.
This should also work, even if the objects in the array are not ordered according to the order property.
The best way to find the last number if there is one would be :
this.templatesDto.length > 0 ? this.templatesDto[this.templatesDto.length-1].order : 1
This way if there isn't an order already it will start at 1.
add() {
const orderNo = this.templatesDto.length > 0 ? this.templatesDto[this.templatesDto.length-1].order + 1 : 1 ;
this.templatesDto.push({
id: 0,
order : orderNo ,
})
}
The previous answers are all correct and will be sufficient for the current state of the Question.
I however would append the case, that the Order might be shuffled or at any point an element would be remove, would eventually cause some issues.
For the case, that an element in the middle would be deleted/removed, it might not cause any trouble, as the SQL-like auto-increment would still work.
But in the case, that the elements would be sorted or shuffled, the methods previously mentioned would fail, as the last element wouldn't be always the highest orderNum.
For the case, that at any point, the case occurs, i would like to submit a method, that takes this case in consideration.
add(){
// We collect the last Order number
const nextOrder = getLastOrderNum();
// We can safely insert the lastOrderNum with a single increment.
// If it is -1 we then insert 0 and so on.
this.templatesDto.push({
id: 0,
order : (nextOrder + 1)
})
}
getLastOrderNum() {
// We iterate through the entire Array and reduce it
// by returning the higher order.
// If the Array has 0 elements, we will return the beginning Value of -1,
// which will latter be incremented to 0.
// With this we can spare some logic to check if the result were 0 and not
// increment.
return this.templatesDto.reduce((a,b) => Math.(a, b.order), -1);
}

How to map specific column using GAS?

From #soMario's answer to a certain question, getting the data of specific column can be done like this:
The following will get columns b,d,f,g from the range A:G.
const rawData = ss.getRange("A:G").getValues().map(([,b,,d,,f,g]) => [b,d,f,g]);
How can I get the same, but using getRange(2,1,sheet.getLastRow(),7) instead?
Thank you!
when you getValues() of any range, it is stored as one array of many arrays, which looks like this, structurally for the range A1:G3 :
[ [ , , , , , , ], [ , , , , , , ], [ , , , , , , ] ]
when you want a specific "column", say column 4 of that range, in javascript/appscript it means you want the 4th element of each of the arrays in the array. When counting from 0, the 4th element is the 3rd "index".
When using the mapping function, each of the elements of the array being mapped is assigned any variable you want. It is common to use "e". So for your specific case you would want to do this
const rawData = ss.getRange("A:G").map(e=>[ e[1], e[3], e[5], e[6] ]);
1,3,5 and 6 being the "indices" of columns B,D,F and G when starting to count with A as 0.
However, it's likely that you'll want a filter on your data as well to only return rows where there are values in column A. If that guess is correct, you can apply a filter before your map like this:
const rawData = ss.getRange("A:G").filter(e=>e[0]).map(e=>[ e[1], e[3], e[5], e[6] ]);

How to display array data inside textbox using loop? (One textbox per array data)

Good day! I badly need help for this one, I have an array with many elements/data that is needed to be display in textbox. Each array element/data must be inside the textbox. (The Textbox must be dynamically set up using loop with the array data inside it)
arr = ["1"-"2"-"3"-"4"-"5"]; //my array is from the db, this is example only
conv_arr = arr.split("-")
var myArray = [conv_arr];
var ArrayInText = document.createElement('input');
myArray.forEach(function(conv_arr) {
ArrayInText.value = conv_arr ;
document.body.appendChild(ArrayInText);
It displays the array (pretend this is a textbox [ ])
[ 1, 2, 3, 4, 5 ]
I want a result that looks like this (One textbox per element using loop)
[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]
You can see the demo here=> https://jsfiddle.net/4ow6k8j5/1/
After removing unnecessary assignments, you can use below simplest solution;
conv_arr = arr.split("-")
conv_arr.forEach(function(elem) {
var ArrayInText = document.createElement('input');
ArrayInText.value = elem ;
document.body.appendChild(ArrayInText);
});

Add values into 2D dimensional array in JS

I'm trying to add values into 2D array based on the position that is present in the input data.
For example, the below format represents 0 as row, 0 as column and 5 is length of the value.
[
"0,0,5",
"hello"
],
How do I insert the values into 2D array based on position like [0][0], [0][1] and [0][2]?
Except from my code
const data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
let array2D = [
[]
];
let i = 0
for (let r = 0; r < data.length; ++r) {
array2D[r] = [];
for (let c = 0; c < data.length; ++c) {
array2D[r][c] = data[i++];
}
}
console.log(array2D);
Ok, thank you for your input.. it means that I'll just make a function to place into an array with 4 arguments.. col,row,arr&data
//important function
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
var array2dArray=[]
//this loop would take the data array and place the entire index in the desired destination
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,array2dArray,a) //the data to put into each part of the 2d array would an array itself(like data[0])
})
console.log(array2dArray)
//but I might just wanna put the text in the 2d array
var text2dArray=[]
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,text2dArray,a[1]) //the data to be put in each part of the 2d array would be the a text variable(like data[0][1] is "hello")
})
console.log(text2dArray)
<script>
//sry it just takes space in the js part that's unnessecary
window.data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
</script>
With this function, you can take an empty array, place row 10 col 4 in empty array putting any data like 'xD' and it will work out eg: try place2d(10,4,emptyArrName,"xD") and it works.. just one thing to note..
IT ONLY APPLIES array structures to WHERE IT NEEDS TO.. doing things like the example above would leave a lot of undefined slots.. wild example below
//now for a wild example to show that the function works
window.data2=[
["text for [10][0]","0/10"],
["text for [2][5]","5/2"]
]
//don't forget the placer function :D
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
//at the end of the day, all I'm changing is the information I make out of the array in the forEach loops in order to simply place in the function
var finalArray=[]
place2d(3,4,finalArray,"randomDataThatCouldBe_ANYTHING_notJustText")
data2.forEach(a=>{
var [col,row]=a[1].split('/')
place2d(row,col,finalArray,a[0])
})
console.log(finalArray)

Javascript printing from nested arrays

I am currently working on a random number generator script that will generate three numbers. The first two numbers will be used to pick a "cell" in a "table" by referencing the row and column. Within each cell are two numbers to choose from. The third number will then determine which of the two numbers to select. I have figured out most of this but I am having problems with the last part.
My "solution" was to create twenty arrays, and within each array are twenty more arrays. Here is an example of the first array:
In the header I have the following:
Scripts to generate the first two numbers:
var randOne20 = Math.floor(Math.random()*20);
var randTwo20 = Math.floor(Math.random()*20);
Here is the first row of the 20 arrays:
var lvl1Roll1 = [[ 1,0 ],[ 1,1 ],[ 1,2 ],[ 1,3 ],[ 1,4 ],[ 1,5 ],[ 1,6 ],[ 1,7 ],[ 1,8 ],[ 1,9 ],[ 1,10 ],[ 1,11 ],[ 1,12 ],[ 1,13 ],[ 1,14 ],[ 1,15 ],[ 1,16 ],[ 1,17 ],[ 1,18 ],[ 1,19 ]];
The second row would be "lvl1Roll2" and the third would be "lvl1Roll3" etc. all the way up to "lvl1Roll20."
In the body I have the following script:
var randOne = randOne20 + 1;
document.write(window['lvl1Roll'+randOne][randTwo20]);
The randOne variable is used to select the appropriate row.
I can figure out how to select a specific cell (using the randTwo20 variable) but I have no idea how to then select the first or the second number within each cell.
Now, just to clarify, I have not listed the third random number generator code because at the moment I am just trying to figure out how to select either the first or second number within each cell. Once I figure that out I can just use an if/else statement.
Also, if I did not want to print out the number but select it as a variable how would I do that?
Thank you for any and all help!
Take care and have a great day....
ciao,
john.
I'm really not sure what you're trying to do, but... Getting the first of second element of an array is as simple as arr[0] and arr[1], like so:
// First:
document.write(window['lvl1Roll'+randOne][randTwo20][0]);
// Second:
document.write(window['lvl1Roll'+randOne][randTwo20][1]);
To randomize, just follow the same pattern as before, but use Math.round instead of Math.floor and don't multiply by 20:
var randOne20 = Math.floor(Math.random()*20);
var randTwo20 = Math.floor(Math.random()*20);
var randOne = Math.round(Math.random());
document.write(window['lvl1Roll'+randOne20][randTwo20][randOne]);
One more thing, though: you don't need to put the different rows in separate variable. You can just make it one big array:
var lvl1Roll = [
[
[ 1,0 ], [ 1,1 ], [ 1,2 ], [ 1,3 ], [ 1,4 ], [ 1,5 ], [ 1,6 ], [ 1,7 ], [ 1,8 ], [ 1,9 ], [ 1,10 ], [ 1,11 ], [ 1,12 ], [ 1,13 ], [ 1,14 ], [ 1,15 ], [ 1,16 ], [ 1,17 ], [ 1,18 ], [ 1,19 ]
],
// [ lvl1Roll2 ],
// [ lvl1Roll3 ], etc.
];
And use then use this to select a value from the table and put it into the variable result:
var result = lvl1Roll[randOne20][randTwo20][randOne];
And finally: I suspect that, I you were to tell us the logic behind the "rolls", it's quite plausible that you don't need this "table" at all. I could be wrong, but... might it be worth posting another question about that? Just a thought.
If you want a random choice between two numbers (assuming 0 and 1), then:
var i = Math.random() < 0.5? 0 : 1;
or
var i = Math.random()*2 | 0;
should do the job. So:
document.write(window['lvl1Roll'+randOne][randTwo20][i]);
or
document.write(window['lvl1Roll'+randOne][randTwo20][Math.random() < 0.5? 0 : 1]);
or
document.write(window['lvl1Roll'+randOne][randTwo20][Math.random()*2 | 0);
How many do you want? :-)
If I understand you correctly I think the easiest way to do this would be with one array that contained multiple arrays. The first would be the table array, each entry in the table array would be a row and each entry in a row would be a cell. This would make it really easy to reference any cell in the table. Here is a 3x3 example:
var table = [
[0,1,2],
[3,4,5],
[6,7,8],
];
table[0][0]; // First Row, First Column, Equals 0;
table[1][1]; // Second Row, Second Column, Equals 4;
table[2][2]; // Third Row, Third Column, Equals 8;
You could actually push your 20 arrays into an array to create the table if you'd like:
var table = [];
table.push(randOne20);
table.push(randTwo20);
etc...
If you want to automatically load the arrays with random numbers you could easily do that with a loop.
var table = [];
for (var i = 0; i < 20; i++){ // Create 20 rows
var row = [];
for (var x=0; i<20; i++){ // Create 20 cells;
var cell = [Math.round(Math.random), Math.round(Math.random)]; // Adds a two item array of random 0's or 1's
row.push(cell); // Adds the cell to the row
}
table.push(row); // Adds the row to table
}

Categories