removing empty rows from an array in javascript - javascript

I have an array with empty rows,I have the field "codeOperation" to test if a row is empty or not,this is my table:
The client should fill the table whith data and left the rest of rows empty, what I want is when the client click on the "ADD" boutton only the data will be send and the emoty rows will be deleted.
this is my code:
//function to send the Data
$scope.updateGamme= function(gamme) {
gamme.listElementGammeOf = $scope.finalOperationsList;
$scope.DeleteEmptyRows(gamme.listElementGammeOf);
$http
.put(
baseUrl +
"/gamme/update",
gamme)
.success(
function(gammeModifiee) {
//send the Data and update
.....
}); }
//delete the empty rows
$scope.DeleteEmptyRows = function(listelements){
for (var i = 0; i < listelements.length; i++) {
if (listelements[i].operationCode == "")
listelements.splice(i, 1);
}
What I get as a result with this code, is that per example I get 5 items, my code will remove the rows 3 and 4 the row 2 is not deleted
Is there any problem with my code? Please help me find it.
Thanks for help

Looks like
for (var i = 0; i < listelements.length; i++) {
if (listelements[i].operationCode == "")
listelements.splice(i, 1);
}
should be
for (var i = 0; i < listelements.length; i++) {
if (listelements[i].operationCode == "")
listelements.splice(i--, 1);
}
When you iterate and remove items from an array, you should decrement your index not to miss an item after the index shift due to removing.

Try splicing in reverse order. i.e remove rows from the last one.
I haven't tried your code but it must work.
$scope.DeleteEmptyRows = function(listelements){
for (var i = listelements.length-1; i >=0; i--) {
if (listelements[i].operationCode == "") {
listelements.splice(i, 1);
}
}
}
The example I tried is...
var array = ["1","2","","",""];
for(var i=array.length-1;i>=0;i--)
{
if(array[i]=="")
array.splice(i,1);
}

Related

Strange behaviour in the if statement

I have a piece of code that is meant to hide table elements depending on given array. I am running loops to compare innerText of one of the cells and the given array.
However, my if statement is statement is acting weird, once i set the operator to === the operation is successful and table rows that match the array are hidden. But i need my if to hide the elements that are not a part of the array, so naturally I set my operator to !== but once i do it it just executes anyway and of course hides all of the elements in the table.
Any idea why this is happening here is the code:
var td1 = document.querySelectorAll("#course");
var rowss = document.querySelectorAll("#rows");
var courseNames1 = [td1.innerText];
var diff = _.difference(soretedArray, courseNames1)
console.log(diff);
for (var i = 0; i < rowss.length; i++) {
for (var j = 0; j < diff.length; j++) {
if (td1[i].innerText === diff[j]) { // if i set the logic operator to !== it hides all of the elements rather the ones that don't match
console.log(rowss[i]);
rowss[i].style.display = "none";
break;
}
}
}
I added the code as I have understood your request: You want the negation of "contains" to hide the element. This is as complete as possible based on the information you gave.
var soretedArray = [];//initialized elsewhere
var td1 = document.querySelectorAll("#course");
var rowss = document.querySelectorAll("#rows");
function tdContains(td) {
for(var j= 0 ; j< soretedArray.length; j++){
if(td.innerText === soretedArray[j]){
return true;
}
}
return false;
}
for(var i = 0 ; i < rowss.length; i++){
if(!tdContains(td1[i])) {
console.log(rowss[i]);
rowss[i].style.display= "none";
}
}

javascript row index update after deleting a row

i'm learning JavaScript and have this assignment where I must build a table where i enter content. Every row must get an index number. And when this works you must be able to input the row number and delete this.
So far, so good.
BUT when i inputted multible rows and deleted the 3rd of 5 rows. And i saw that the row index numbers go from 1, 2, 4, 5. So it doesnt update. Now i want to fix that.. but how?!
I cant think of a way to only call uppon the 1st number of every row..
I hope you can help me..
The link to my project(sorry in advance, i am dutch!):
https://jsfiddle.net/Burner/kaqsgra1/
My loops for inputting the rownumber:
function addContent(){
for(i = 0; i < f.length; i++){
newData[i] = f.elements[i].value;
}
var newRow = contenttable.insertRow();
for (var i = 0; i< 4; i++){
newData[0] = contenttable.rows.length - 1;
var newCel = newRow .insertCell(i);
newCel.innerHTML = newData[i];
}
}
And when deleting a number i call this function:
function deleteNumber(){
var numRows = contenttable.rows.length - 1;
if(deleteNr.value == ""){
alert("Voer svp een nummer in!");
return false;
}
if(deleteNr.value > numRows){
alert("Dit rijnummer bestaat niet ");
return false;
}
document.getElementById("uitvoertabel").deleteRow(deleteNr.value);
}
In your deleteNumber function, renumber your rows after the selected row is deleted.
for (var i = 0; i< uitvoertabel.rows.length; i++){
uitvoertabel.rows[i].cells[0].innerHTML = i;
}
JSFiddle

Match two rows in google script

I'm new to google script and I want to compare two rows from two sheets & if any cell data value matches it'll increase a value. But I'm getting an error like this,
TypeError: Cannot read property "0" from undefined.
Here are my codes,
function onFormSubmit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 1");
var ans_sheet = ss.getSheetByName('Correct_Answers');
var getValues = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
var realValues = ans_sheet.getRange(2, 1, ans_sheet.getLastRow(), ans_sheet.getLastColumn()).getValues();
for (var i in getValues) {
for (var j in getValues[i]) {
var matched = 0;
if (getValues[i][j] == realValues[i][j]) {
matched++;
} else {
getValues.push(1);
}
}
}
I know I'm doing something wrong here but since I'm new I can't figure it out. Need this help badly from experts. Thanks.
This could be because the two ranges have different lengths or because you are appending 1's to the first array in which case there is also nothing to subscript.
At some point you are trying to access the first column (index 0) of a row that is not in the other range or the first column of 1 which does not exist.
since you are iterating through getValues you can do a check at the beginning of the loop.
for (var i in getValues) {
if(i == realValues.length){break;}
for (var j in getValues[i]) {
if(j == realValues[j].length){break;}
var matched = 0;
if (getValues[i][j] == realValues[i][j]) {
matched++;
}
}
}

Panels not adding to columns

What I am trying to achieve is to allocate a panel to the column with the least amount of panels in it, and if 2 of the columns have an equal amount of panels then I take the first column and insert it there. I have attempted to implement this, which I will show below however I want to first address the problem that I am having. I understand that my code may have many flaws, and so I am open to suggestion on how to make it better. so the error I am getting through firebug is
TypeError: columns[leastItems] is undefined
return columns[leastItems].id;
and here is my javascript code that I have implemented:
function DashboardAllocation() {
var columns = document.querySelectorAll('.col-md-4.column');
var noElemsInCol = new Array(columns.length);
//Get count of children in each column into array
for (var columnNumber = 0; columnNumber < columns.length; columnNumber++) {
noElemsInCol.push(countChildren(columns[columnNumber]));
}
//Compare all values to see if they are all the same or if the first column is 0
if (compareAllValues(noElemsInCol) || countChildren(columns[0] === 0)) {
//if it is then return the first columns id
return columns[0].id;
}
//Reference http://www.programmingsimplified.com/c/source-code/c-program-find-minimum-element-in-array
var leastItems = 1;
var minimum = countChildren(columns[0]);;
for (var i = 1; i < noElemsInCol.length; i++) {
if (noElemsInCol[i] < minimum) {
minimum = noElemsInCol[i];
leastItems = i + 1;
}
}
return columns[leastItems].id;
}
//Compares all the values in the array to check if they are equal
//Reference http://stackoverflow.com/questions/9973323/javascript-compare-3-values
function compareAllValues(a) {
for (var i = 0; i < a.length; i++) {
if (a[i] === null) { return false }
for (var j = 0; j < i; j++) {
if (a[j] !== a[i]) { return false }
}
}
return true;
}
function countChildren(Nodes) {
var childrenCount = 0;
for (var nodeType in Nodes.childNodes) {
//if the nodetype is an element then we will add one
if (nodeType == Node.ELEMENT_NODE) {
childrenCount++;
}
}
return childrenCount;
}
I have referenced the sources where I took code from and hope it helps to see where I am coming from and understand what I am trying to do
You are getting problem as an index leastItems of the array columns is out of range.
Currently You are getting error as in an array of [5] you are trying to fetch the sixth element, using leastItems variable
So either use change
var leastItems = 0;
OR, Use
return columns[leastItems -1 ].id;

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

Categories

Resources