I'm trying to get array index by value.
I have this code:
var squares = new Array();
for (var i = 1; i <= 160; i++) {
squares.push(i);
}
angular.element('.click').click(function () {
var squareId = angular.element(this).attr('id');
var fisk = squares.indexOf(squareId);
console.log(fisk);
});
This only returns -1, thus, It can't be found. If a replace squareId with a number in indeOf, it works perfect, but if I use a variable, It don't work.
Anyone who can help me?
You are initializing your array values with numbers between 1 and 160, so squares.indexOf(1) for example would return 0.
What you want to do is initialize the array with the actual ids of your elements.
See Example Fiddle
It's because the variable squareId could be returning a string value. The function indexOf can't find the string because it has numbers in the array.
// string search
var squareId = '2';
var fisk = squares.indexOf(squareId);
console.log('This will not be found ' + fisk);
// number search
var squareId = Number('2');
var fisk = squares.indexOf(squareId);
console.log('This will be found ' + fisk);
See similar question
Related
I have a function that I have modified to get a string (which consists of zeros and ones only).
The string (timesheetcoldata):
100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000
The string items (the numbers one and zero) will change every time the function is run.
It will always be the same length.
I have made the string above easier to see what I am trying to achieve.
I want to return the first character and then every 24th character (as in the variable colsCount in the function).
so, in the example above, it would return something like: 111111
I then want to convert these characters to numbers (something like [1, 1, 1, 1, 1, 1]).
I then want to sum these number together (so it would return, in the example: 6).
I then want to check if the returned number matches the variable: rowsCount
or true if it does, false if it does not.
My function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var colsCount = 24;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
console.log(timesheetcoldata);
});
Thank you very much to both Rajesh and MauriceNino (and all other contributers).
With their code I was able to come up with the following working function:
$("#J_timingSubmit").click(function(ev){
var sheetStates = sheet.getSheetStates();
var rowsCount = 6;
var timesheetrowsdata = "";
var timesheetcoldata = "";
for(var row= 0, rowStates=[]; row<rowsCount; ++row){
rowStates = sheetStates[row];
timesheetrowsdata += rowStates+(row==rowsCount-1?'':',');
}
timesheetcoldata = timesheetrowsdata.replace(/,/g, '');
var count = 0;
var list = [];
for(var i = 0; i< timesheetcoldata.length; i+=24) {
const num1 = Number(timesheetcoldata.charAt(i));
list.push(num1);
count += num1;
}
let isSameAsRowsCount = count == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
});
You can always rely on traditional for for such action. Using functional operations can be more readable but will be more time consuming(though not by much).
You can try this simple algo:
Create a list that will hold all numbers and a count variable to hold sum.
Loop over string. As string is fixed, you can set the increment factor to the count(24).
Convert the character at given index and save it in a variable.
Push this variable in list and also compute sum at every interval.
At the end of this loop, you have both values.
var string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
var count = 0;
var list = [];
for(var i = 0; i< string.length; i+=24) {
const num1 = Number(string.charAt(i));
list.push(num1);
count += num1;
}
console.log(list, count)
Here is a step by step explanation, on what to do.
Use match() to get every nth char
Use map() to convert your array elements
Use reduce() to sum your array elements
Everything needed to say is included in code comments:
const testData = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
// Step 1) Create array of numbers from string
const dataArr = testData.match(/.{1,24}/g) // Split on every 24th char
.map(s => Number(s[0])) // Only take the first char as a Number
console.log(dataArr);
// Step 2) Sum array Numbers
let dataSum = dataArr.reduce((a, b) => a + b); // Add up all numbers
console.log(dataSum);
// Step 3) Compare your variables
let rowsCount = 123; // Your Test variable
let isSameAsRowsCount = dataSum == rowsCount;
console.log('Is Same? ', isSameAsRowsCount);
As #Jaromanda mentioned, you can use the following to done this.
const string = '100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000100000000000000000000000';
const value = string.split('').filter((e,i)=> !(i%24)).reduce((acc,cur)=> acc+ (+cur), 0);
console.log(value);
This question already has answers here:
How to add same elements to javascript array n times
(4 answers)
Closed 4 years ago.
I've been trying to figure this problem out for a while but I'm at a blank. Here's what I have so far:
var repeatNumbers = function(data) {
var repeated = [];
for ( var x = 0; x < data.length; x++){
var unit = data[x][0]
var quant = data[x][1]
for(var i = quant; i > 0; i--){
repeated.push(unit);
repeated.join(',');
}
return repeated;
}
};
console.log(repeatNumbers([1, 10]));
Basically I'm trying to repeat the first number of the array based off of the second value. Any insight would be greatly appreciated thank you! :)
You don't need to loop over your array if you only have two numbers, where the first number (at index 0) is the number you want to repeat, and the second number is the number of times you want to repeat that number (index 1).
Once you have the number of times you wish to repeat the number, you can simply use a for loop to enter the number into your repeated array that number of times.
See working example below (read code comments for further explanation):
var repeatNumbers = function(data) {
var repeated = []
var toRepeat = data[0]; // get the first number in the array
var times = data[1]; // get the second number in the array
// loop the number of times you want to repeat the number:
for(var i = 0; i < times; i++) {
repeated.push(toRepeat); // push the number you wish to repeat into the repeated array
}
return repeated.join(); // return the joined array (as a string - separated by commas)
}
console.log(repeatNumbers([1, 10]));
If I understand your question correctly, you want the function repeatNumbers() to return an array with the first element in the passed array replicated by the second element in the passed array.
To achieve that, you could do the following:
var repeatNumbers = function(data) {
// Extract the "value" to be repeated, and the "repeated" value
// that will control the number of "value" items in result array
var value = data[0];
var repeated = data[1];
var result = []
// Loop over repeated range, and push value into the result array
for (var i = 0; i < repeated; i++) {
result.push(value);
}
// Result result array
return result;
};
console.log(repeatNumbers([1, 10]));
Or, if you don't need to support IE, a more consise approach would be:
var repeatNumbers = function(data) {
var value = data[0];
var repeated = data[1];
return (new Array(repeated).fill(value));
};
console.log(repeatNumbers([1, 10]));
So i have this string
first €999, second €111
Im trying to make an array that looks like this (numbers after every €)
999,111
Edit:
Yes i have tried to split it but wont work. i tried to look it up on google and found something with indexof but that only returned the number of the last €.
rowData[2].split('€').map(Number);
parseInt(rowData[2].replace(/[^0-9\.]/g, ''), 10);
split(rowData[2].indexOf("€") + 1);
The numbers are variable.
var input ="first €999, second €111";
var output=[];
var arr = input.split(",");
for(var i=0;i<arr.length;i++)
{
output.push(parseInt(arr[i]));
}
var output_string = output.stingify();
console.log(output); //Output Array
console.log(output_string); //Output String
If the numbers will always be of 3 digits in length, you can do this. If not, you need to specify a bit more.
var string = "€999, second €111";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].substring(temp[i].indexOf("€"),3));
}
//digitArray now contains [999,111];
Edit, based on your requirement of variable digit lengths
var string = "€999, second €111, third €32342";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].replace(/^\D+/g, '')); //Replace all non digits with empty.
}
//digitArray now contains [999,111,32342]
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')
So why myarray[bla][bl] always equal to NaN? If I do the same thing with 1 dimension (myarray[bla]), I get the number.
var bla = 'blabla';
var bl = 'bla';
var myarray = [];
for (i = 0; i < 10; i++) {
if (!myarray[bla]) {
myarray[bla] = [];
}
myarray[bla][bl] += i;
console.log(myarray[bla][bl] + " + " + i);
}
Ok, so let's step through your loop, replacing instances of the variable bla with the string value of 'blabla':
if (!myarray['blabla']) {
myarray['blabla'] = [];
}
Arrays in javascript are index by integer values. What your code here is doing is adding an expando property to the array instance named blabla. That is:
myarray.blabla = [];
now reconsider your increment statement:
myarray['blabla'][bl] += i;
or, with the expando properties:
myarray.blabla.bl // remember that "myarray.blabla" is set to the empty array above
What this is trying to do is access the property named bl on the empty array. That's why you're getting undefined here.
Anyway, as a best practice, you might want to avoid using arrays in javascript like hashtables, since problems like this are bound to crop up after enough time.
If we expand a little I hope you can see the problem,
if (!myarray[bla]) {
myarray[bla] = [];
}
myarray[bla][bl] = myarray[bla][bl] + i;
Hint: myarray[bla][bl] = undefined
because myarray[bla][bl] is not set... , you need
if ( !myarray[bla][bl] ){ myarray[bla][bl] = 0; }