Javascript for() to add values to array - javascript

I have a program that displays errors like this:
wifi : 298
So, it says the type of error and the number.
Right now there are 8 errors, which I have divided by type and number, so 16 values. I would like to add them to an array like:
var array{type:'____', number:'____'}
I would like to add the values via function, so it can be automatic, in case I add ou remove errors to display, a for seems the best way to do it.
Problem is.. I'm horrible at math..
I've tried a for where i starts at -1 and its i++. The type would be value[i+1] and the number would be value[i+2].
This would be the result:
i=-1
type=value[0]
number=value[1]
i=0
type=value[1]
number=value[2]
So you see, value[1] appears twice:
0
1
1
2
When it should only appear once:
0
1
2
3
var errorSplit = errorlog.split(/:|;/);
var errors;
for(var i=-1;i<16;i++){
errors= {type: errorSplit[i+1], num: errorSplit[i+2]};
}

Just up it by 2 on every iteration. I would also suggest slight changes for readability (Replacing -1 by 0 and changing index acccessors).
You need to make the errors array an actual array and add things to it not overwriting them.
You can make the loop variable length too by just using the errorSplit length as a limiter.
var errorSplit = errorlog.split(/:|;/);
var errors=[]; // Make the array an actual array
for(var i=0; i<errorSplit.length; i+=2) { // Start at index 0, go until there are no errorSplit parts left, up it by 2 every iteration
if(errorSplit.length<(i+1)) // If the index is higher than errorSplit+1, exit the loop
break;
errors.push({type: errorSplit[i], num: errorSplit[i+1]}); // Add the element to the array
}

Related

What is the function of 'i' in for loop in JavaScript when accessing arrays?

const rapperArray = ['Tupac', 'Jay-Z', 'Notorious B.I.G', 'Kendrick Lamar']
for (let i = 0; i < rapperArray.length; i++) {
console.log(rapperArray[i]);
if (i === 2) {
break;
}
}
console.log("And if you don't know, now you know.");
So how does i work in that console.log( rapperArray[ i ] );? I know that it accesses the elements in the array but I can't seem to get my head around how it actually functions.
The i is a variable. In a for loop, you have the following syntax:
for(initialization; condition; update) {
// for loop body
}
The for loop will begin by running the initialization portion first, which in this case declares the variable i with an initial value of 0. Before each iteration of the loop, condition is checked and the loop body will run as long as condition is true. Then, after the loop body runs, update will run. In this case, the variable i will have its value incremented by 1, i.e. i++ is basically the same thing as i += 1.
In other words, the for loop will use every value of i from 0 up until rapperArray.length - 1. So console.log(rapperArray[i]); will be the same as console.log(rapperArray[0]); in the first iteration, console.log(rapperArray[1]); in the second iteration, and so on.
You can see this more clearly by running the following:
const rapperArray = ['Tupac', 'Jay-Z', 'Notorious B.I.G', 'Kendrick Lamar'];
for (let i = 0; i < rapperArray.length; i++) {
console.log('When i is ' + i + ', rapperArray[i] is ' + rapperArray[i] + '.');
}
A for loop header consists of three parts:
Initial state let i = 0
Condition to check if loop should continue i < length
Increment per run i++
We start with 0, in the beginning i is lower than length, then we up it by 1 (i++ increases i by 1), if it's still lower than length - we continue until i has the same value as length and then we stop.
It indicates the current iteration of the loop. For each iteration, i is incremented. When used to get an array item, it represents the index of the item to retrieve from the array. You can read more about indexed collections here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections
Arrays in JavaScript are zero-index based, which means the first index is always zero. And they increment from there. Arrays are ordered collections, so the item at the first index (zero) is always the same, and so on.
If you have a list on paper in front of you, you may number the lines starting with 1 and going up from there. Each item in an array is somewhat like each line on that piece of paper, only the line numbers start at zero instead of one. If you want to get line n from the paper, you find the line numbered n and there you go.

Set value to an array in pentaho javascript step

i have some values in the input and i want to save them into an array but first i want to set the "0" index of the array to 0 and then in the 1,2,3,4 indexs add the value of the input but i can get to make it
before to set the values of the input i set the 0 to the position 0 of the array but it doesnt work
the thing is that i want to use only the first four number of the input_data into an array but first set the 0 position to 0 and then add 5,10,15,20.
so the final array would be 0,5,10,15,20
i set the index "0" of the array to 0 and the other indexes i fill them whit the incoming data.
This depends on how the data is reaching the 'Modified Java Script Value' step.
If it is one single row, with the string containing a "CSV", then Rohit.007 answer will suffice.
If you have multiple rows reaching the step, the Script will Repeat N(row) times. If you have 4 rows being fed to the step, this script will run 4 times, so you need some sort of restraint on the Variables, so you don't repeat some parts of the code.
Personally i would use something like this for Pentaho:
I generated 4 rows, with an add sequence , 1 to 4.
The first run of the script creates the array, pushes 0 and the value of the first row. The other iterations of the script just keep pushing whatever values are found on the specified row to this array (without "Re-declaring" it).
Remenber that the "For Each" command is kind of blurred in pentaho, since you're almost always dealing with multi-row tables, so whatever you do in scripts has to have some constraints on variables declarations.
You can try the below code.
let array = [];
array.push(0);
let string = '1,2,3,4';
array = array.concat(string.split(','));
let result = array.map(function (x) {
return parseInt(x, 10);
});
console.log(result);

JavaScript - Array "undefined" error

I got a problem with this simple piece of code which i cant figure out.
Instead of printing the whole array in the console, i get the message "10 undefined". Altough if i put "var i" to 0 or below then it's all good and i get a full list from that number up to 10.
Why wont this work when "i" is set to a number above 0?
Took a picture of my console in chrome to show how it looks like:
var ar = [];
for (var i = 1; i <= 10; i++) {
ar.push(i);
console.log(ar[i]);
}
JavaScript array indices start at 0, not 1. The .push() method adds an element at the end of the array, which in the case of an empty array (as yours is when your loop begins) will be array element 0.
Your loop inserts the value 1 at array index 0, the value 2 at array index 1, and so forth up to the value 10 at array index 9.
Each of your console.log(ar[i]) statements is trying to log a value from an index one higher than the highest element index, and those elements will always be undefined. So the console logs the value undefined ten times.
You can log the last element of an array like this:
console.log(ar[ar.length-1]);
Or in your case where you (now) know that i will be one higher than the index that .push() used:
console.log(ar[i-1]);
"10 undefined" means that the console showed "undefined" 10 times.
As thefourtheye says in his comment, you're pushing the value i but the index of the element that you just pushed onto the end of the array is i - 1. This means that each time you console.log(ar[i]) you're logging something that's not yet defined.
This is all because the first element in the array is ar[0], not ar[1]. You can fix your problem by logging like so: console.log(ar[ i - 1 ]);
Because array indices start at zero. The current index is undefined that's why you get those. Try this instead:
var ar = [];
for(var i = 1;i <= 10;i++){
ar.push(i);
console.log(ar[i-1]);
}

Cleanest way to check all sub-arrays are defined

I was just writing a little game of life script, seen as I'd never really done it. I have created a matrix array that has sub arrays of columns, each containing the values of each row in that column. When I loop through to check the neighbours I want to count them like the below:
var count = 0;
count += this.data[i-1][j-1];
count += this.data[i-1][i];
count += this.data[i-1][j+1];
count += this.data[i][j-1];
count += this.data[i][j+1];
count += this.data[i+1][j-1];
count += this.data[i+1][i];
count += this.data[i+1][j+1];
Obviously on the i-1 and i+1 indexes will cause a problem at the beginning and end of the arrays. I can check for undefined on the value of the rows (the deepest value) like so:
count += typeof this.data[i-1][j-1] !== 'undefined' ? this.data[i-1][j-1] : 0;
But if the columns array is undefined obviously it will error and I can't check this without writing a few more lines. Is there anyway I can catch this error in this one line, or is there a quicker way to get this data. I just don't want lots of try/catches or if/elses to account for the edges of the matrices?
I know I could remove the sub-array structure and just have one long array of data but I was just curious about efficient ways of dealing with this structure.
"Cleanest" is a subjective term, but three possibilities for you:
Use JavaScript's curiously powerful || operator:
count += (this.data[i-1] || [])[j-1] || 0;
That works for two reasons:
In JavaScript, accessing an array index that doesn't exist returns undefined. It doesn't cause an error.
Unlike many programming languages, JavaScript's || returns its first operand if that operand is truthy and its second operand if not, rather than a boolean. Truthy values are values that aren't falsey; falsey values are 0, undefined, null, "", NaN, and of course false. So 1 || 0 is 1, undefined || 0 is 0, and 0 || 0 is also 0.
Note that the || [] part of that won't create an array unless the this.data[i-1] part is undefined. But if you're worried about creating temporary arrays like that, you could have just one defined throughout your script (var blank = [];) and then use it:
count += (this.data[i-1] || blank)[j-1] || 0;
Define your arrays (both the "vertical" one and all the "horizontal" ones) two elements too big and set the values around the edges to 0. Then loop from 1 to < length - 1, and you don't have to worry about going out of bounds because the -1 case will take you to the 0th element, which has the value 0, and the +1 case will take you to the length-1 element, which also has the value 0. This offers quite clean code at the expense of a small bit of extra memory. Or:
Have a function to get the value which checks the coordinates and returns 0 if either is invalid. This offers quite clean code at the expense of a small bit of added overhead.

JavaScript TypeError when indexing into 2D array

I am working on some code that manipulates a 2D array of "cell" objects.
function randomDestFromStart(cell, temp)
{
function addPossible(x, y)
{
var test1 = temp[x];
var test2 = test1[y]; // This line
// ... //
}
for (var i = 0; i < temp[0].length; i++)
addPossible(cell.x, i);
// ... //
}
temp is the 2d array, and cell is a particular Cell object. Defining test2 results in the following error:
TypeError: test1 is undefined
I have confirmed in the debugger that x and y are valid integers (in this particular case they are 0 and 1 respectively). temp is a valid array consisting of 5 subarrays of Cell objects, so there shouldn't be any sort of index out of bounds error. There doesn't seem to be an issue indexing one level into temp seeing as test1 is a valid array of 5 cells (essentially a row of temp). The problem is when I index into the 2nd dimension of the array, which is strange since indexing into the same exact array works in other parts of the code.
EDIT: The problem seems to be with the inputs for x and y. When I hardcode these values everything works fine. For example, addPossible(2, 3) works. The error occurs when the values are provided dynamically, but this is strange because the debugger shows x and y as completely normal and valid integers even in these cases. I am 99% sure this is NOT an out of bounds issue. I have checked and the array is 5x5, and x and y are always between 0 and 4.
Most likely your temp array is larger than whatever value exists in cell.x. Its also possible that cell.x is one too big and you want cell.x -1

Categories

Resources