i'm filling an array from the input fields and i need to find the biggest number in that array.
Using Math.max(myData) gives me NaN error and when i'm using the "if" statement,sometimes it works and sometimes it doesn't.
Example: if i have 40 and 100 in array ,it gives me 40 as bigger number,but when i have 500 than it works fine.
if i want to make Math.max to work i need to make a new function that converts string into numbers,right?
my code,so you can see where is the mistake.
function Data() {
var h = 0;
var secnd = 1;
var najBr = 0;
for (var i = 0; i < valGrup2; i++)
{
var first = 1;
myDataName[i] = document.getElementById('ime' + secnd).value;
for (var j = 0; j < val2; j++)
{
myData[h] = document.getElementById("inputpolja" + first + secnd).value;
if(myData[h]>najBr){
najBr=myData[h];
}
myDataValue[h] = document.getElementById("inputpolja" + first + secnd).value;
h++;
first++;
}
secnd++;
}
//najBr=Math.max(myData);
console.log(najBr);
Math.max accepts only plain numbers, not an array.
Use this:
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
Math.max takes multiple arguments, not an array of the numbers. You can use Function#apply() to have it treat the array as a list of arguments:
Math.max.apply(null /* the context */, myData)
Related
Observe:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
The actual result in extendscript would be ... grouplinks ... empty.
If I would change this example to be:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
It would work perfectly. The only change is the missing "59" at the start of the string used for the array key.
Note that this works perfectly when I run it in console for chrome or firefox. It seems to be indesign and/or extendscript fooling around.
Anything have any ideas why ? I've meanwhile worked around the problem but I'm intrigued.
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
That's exactly what it does, but the way you're viewing the data is likely concealing it because you're not using the proper data structure. Also, property access won't work without using [] because identifiers may not start with a number, so you'd need:
groupedLinks["59notgonnawork0"]
What you're doing isn't meant for arrays, which are expecting sequential numeric indices (though they can technically be assigned other properties too). The type of structure you should be using is a plain object instead.
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
const linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array; // Array? plain Object? Depends on its use.
}
Why not trying to push the value in the array on each iteration.
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks.push(linkName);
}
ExtendScript Arrays are great for stocking data per indeces. If you need key/values objects, why not use… Objects ?
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = "Whatever…";
}
alert( groupedLinks["59notgonnawork0" ] ); //"Whatever…"
Ok so I am trying to access each individual number in the strings inside of this array.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
var str = "";
for (i=0; i<array.length; i++) {
str = array[i];
}
The problem is that this is the output: '999-992-1313'
and not the first element array[0]: '818-625-9945'
When I try doing a nested for loop to go through each element inside the string I am having trouble stating those elements.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
console.log(array[i][j]);
}
}
I do not know how to access each individual number inside of the string array[i]. I would like to find a way to make a counter such that if I encounter the number '8' I add 8 to the total score, so I can take the sum of each individual string element and see which number has the highest sum.
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
if (array[i](j).indexOf('8') !== -1) {
// add one to total score
// then find a way to increase the index to the next index (might need help here also please)
}
}
}
Mabe this works for you. It utilized Array.prototype.reduce(), Array.prototype.map() and String.prototype.split().
This proposal literates through the given array and splits every string and then filter the gotten array with a check for '8'. The returned array is taken as count and added to the return value from the former iteration of reduce - and returned.
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.reduce(function (r, a) {
return r + a.split('').filter(function (b) { return b === '8'; }).length;
}, 0);
document.write('Score: ' + score);
A suggested approach with counting all '8' on every string:
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'],
score = array.map(function (a) {
return a.split('').filter(function (b) { return b === '8'; }).length;
});
document.write('Score: ' + score);
Actually rereading your question gave me a better idea of what you want. You simply want to count and retrieve the number of 8's per string and which index in your array conforms with this maximum 8 value. This function retrieves the index where the value was found in the array, how many times 8 was found and what is the string value for this result. (or returns an empty object in case you give in an empty array)
This you could easily do with:
'use strict';
var array = ['818-625-9945', '999-992-1313', '888-222-2222', '999-123-1245'];
function getHighestEightCountFromArray(arr) {
var max = 0,
result = {};
if (arr && arr.forEach) {
arr.forEach(function(value, idx) {
var cnt = value.split('8').length;
if (max < cnt) {
// found more nr 8 in this section (nl: cnt - 1)
max = cnt;
// store the value that gave this max
result = {
count: cnt - 1,
value: value,
index: idx
};
}
});
}
return result;
}
console.log(getHighestEightCountFromArray(array));
The only thing here is that when an equal amount of counts is found, it will still use the first one found, here you could decide which "maximum"
should be preferred(first one in the array, or the newest / latest one in the array)
OLD
I'm not sure which sums you are missing, but you could do it in the following way.
There I first loop over all the items in the array, then I use the String.prototype.split function to split the single array items into an array which would then contain ['818', '625', '9945']. Then for each value you can repeat the same style, nl: Split the value you are receiving and then loop over all single values. Those then get convert to a number by using Number.parseInt an then all the values are counted together.
There are definitelly shorter ways, but this is a way how you could do it
'use strict';
var array = ['818-625-9945','999-992-1313','888-222-2222','999-123-1245'],
sumPerIndex = [],
totalSum = 0;
array.forEach(function(item, idx) {
var values = item.split('-'), subArray = [], itemSum = 0;
values.forEach(function(value) {
var singleItems = value.split(''),
charSum = 0;
singleItems.forEach(function(char) {
charSum += parseInt(char);
});
itemSum += charSum;
subArray.push(charSum);
console.log('Sum for chars of ' + value + ' = ' + charSum);
});
sumPerIndex.push(subArray);
totalSum += itemSum;
console.log('Sum for single values of ' + item + ' = ' + itemSum);
});
console.log('Total sum of all elements: ' + totalSum);
console.log('All invidual sums', sumPerIndex);
I want to do something like:
var arr = []
for var(i=0;i<x;i++){
arr.push{ get num(){return this.previousArrayElement.num + randomNumber}}
}
how can I treat "previousArrayElement"?
I think you are just trying to create an array of size x containing numbers in order of size and separated by randomNumber intervals? Something like this would work:
var x = 100;
var arr = [0]
for (i=1; i<x; i++) {
arr.push( arr[i-1] + Math.random() );
}
Note that by starting the array out with an initial value (index 0) and beginning your iteration with the second value (index 1) you don't have to worry about accessing the 0-1 element at the first iteration.
I hope that helps!
Not 100% sure this is what you want. Expected output shown is not valid syntax and details provided are very open to interpretation
var arr = []
for (var i=0; i < x; i++){
var num = i > 0 ? arr[i-1].num : 0;
num= num + randomNumber; // is this an existing variable?
arr.push({ num: num}); // used object with property `num` based on example `previousArrayElement.num `
}
I'm am working on a script to count the number of times a certain string (in this case, coordinates) occur in a string. I currently have the following:
if (game_data.mode == "incomings") {
var table = document.getElementById("incomings_table");
var rows = table.getElementsByTagName("tr");
var headers = rows[0].getElementsByTagName("th");
var allcoord = new Array(rows.length);
for (i = 1; i < rows.length - 1; i++) {
cells = rows[i].getElementsByTagName("td");
var contents = (cells[1].textContent);
contents = contents.split(/\(/);
contents = contents[contents.length - 1].split(/\)/)[0];
allcoord[i - 1] = contents
}}
So now I have my variable allcoords. If I alert this, it looks like this (depending on the number of coordinates there are on the page):
584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519,,
My goal is that, for each coordinate, it saves how many times that coordinate occurs on the page. I can't seem to figure out how to do so though, so any help would be much appreciated.
you can use regular expression like this
"124682895579215".match(/2/g).length;
It will give you the count of expression
So you can pick say first co-ordinate 584 while iterating then you can use the regular expression to check the count
and just additional information
You can use indexOf to check if string present
I would not handle this as strings. Like, the table, is an array of arrays and those strings you're looking for, are in fact coordinates. Soooo... I made a fiddle, but let's look at the code first.
// Let's have a type for the coordinates
function Coords(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
return this;
}
// So that we can extend the type as we need
Coords.prototype.CountMatches = function(arr){
// Counts how many times the given Coordinates occur in the given array
var count = 0;
for(var i = 0; i < arr.length; i++){
if (this.x === arr[i].x && this.y === arr[i].y) count++;
}
return count;
};
// Also, since we decided to handle coordinates
// let's have a method to convert a string to Coords.
String.prototype.ToCoords = function () {
var matches = this.match(/[(]{1}(\d+)[|]{1}(\d+)[)]{1}/);
var nums = [];
for (var i = 1; i < matches.length; i++) {
nums.push(matches[i]);
}
return new Coords(nums[0], nums[1]);
};
// Now that we have our types set, let's have an array to store all the coords
var allCoords = [];
// And some fake data for the 'table'
var rows = [
{ td: '04.shovel (633|455) C46' },
{ td: 'Fruits kata misdragingen (590|519)' },
{ td: 'monster magnet (665|506) C56' },
{ td: 'slayer (660|496) C46' },
{ td: 'Fruits kata misdragingen (590|517)' }
];
// Just like you did, we loop through the 'table'
for (var i = 0; i < rows.length; i++) {
var td = rows[i].td; //<-this would be your td text content
// Once we get the string from first td, we use String.prototype.ToCoords
// to convert it to type Coords
allCoords.push(td.ToCoords());
}
// Now we have all the data set up, so let's have one test coordinate
var testCoords = new Coords(660, 496);
// And we use the Coords.prototype.CountMatches on the allCoords array to get the count
var count = testCoords.CountMatches(allCoords);
// count = 1, since slayer is in there
Use the .indexOf() method and count every time it does not return -1, and on each increment pass the previous index value +1 as the new start parameter.
You can use the split method.
string.split('517,594').length-1 would return 2
(where string is '584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519')
I have two arrays set up that I wish to multiply each value within each together. Then I want to get the total value in the form of a variable. I will post what I have below. I think my problem may be that I am not sure how to get each run of the code to add together?
var flatQty=[];
flatQty[0]= document.getElementById("flats1").value;
flatQty[1]= document.getElementById("flats2").value;
flatQty[2]= document.getElementById("flats3").value;
flatQty[3]= document.getElementById("flats4").value;
flatQty[4]= document.getElementById("flats5").value;
var flatWidth=[];
flatWidth[0]=document.getElementById("flatwidth1").value;
flatWidth[1]=document.getElementById("flatwidth2").value;
flatWidth[2]=document.getElementById("flatwidth3").value;
flatWidth[3]=document.getElementById("flatwidth4").value;
flatWidth[4]=document.getElementById("flatwidth5").value;
for (var i=0;i<5;i++)
{
var flatCharge=flatWidth[i]*2*flatQty[i];
}
document.getElementById("flatTest").innerHTML=flatCharge;
When I run the code nothing is printed into the id="flatTest".
Your problems is that you are redefining your flatCharge inside the loop, therefore it's not correct outside the loop. In addition, you are not adding the values, but replacing them on every iteration of the loop. Change the loop to this:
var flatCharge = 0;
for (var i = 0; i < 5; i++) {
flatCharge += flatWidth[i] * 2 * flatQty[i];
};
document.getElementById("flatTest").innerHTML = "" + flatCharge;
and it should work.
.value properties are strings, not numbers. so you should be careful how you handle them. Multiplication actually works for strings, but not for addition where the + operator performs concatenation instead.
There are numerous methods of converting from string to number:
+s - will convert the expression s into a number
parseFloat(s)
parseInt(s, 10) for whole numbers
The actual problem in your code is that you're overwriting the calculated value in each pass using the = operator instead of +=.
I suggest refactoring your entire code thus to avoid all of the repetition:
var flatCharge = 0;
for (var i = 1; i <= 5; ++i) {
var qty = +document.getElementById('flats' + i).value;
var width = +document.getElementById('flatwidth' + i).value;
if (!isNaN(qty) && !isNaN(width)) {
flatCharge += 2 * qty * width;
}
}