Does anybody know what is the meaning of this declaration in JS:
var m = [[0]];
I mean what is declarated as type, and why the zero is in the brackets?
[0] is an array with the first index is equal to 0
[[0]] Is an array with its first index equal to an array (whos first index is 0)
It would probably be easier to imagine if you had more elements and space it a bit better:
var m = [[0,1,2],[2,4,5],[1,3]]
so
m[0] = [0,1,2];
m[1] = [2,4,5];
m[2] = [1,3];
This can then be expanded for however many dimensions you need leading to collections of collections of collections.
you can then access each index and use it as the array your referencing for instance:
m[0].push(4);
m[2].join(',');
etc.
(as mentioned above) You can also then access it shorthand like:
m[0][0]
m[x][y]
m[n-1][m[0][1]]
Making it as complicated or simple as you need.
m has been declared as an array, with a nested array inside it, and the nested array contains a single element - 0
console.log(m[0][0]) will output 0
Related
This question already has answers here:
Loop through an array in JavaScript
(46 answers)
What is the difference between ( for... in ) and ( for... of ) statements?
(18 answers)
Closed last year.
I am writing a simple javascript code to parse, and verify a chess position written in Forsyth–Edwards Notation (FEN).
The default chess position in this notation is given by,
const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
There are 6 components, I split the components by whitespace using String.split(" "), I now want to further split the first element of the resulting array by "/", which will give the state of each rank.
Running this code gives me an unintuitive result...
const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
const locations = defaultFEN.split(" ")[0];
for (let rank in locations.split("/")) {
console.log(rank);
}
I expected the output to be 8 Strings, delimited by "/", in the first portion of the defaultFEN string. Instead I get the numbers 0-7 printing out.
Interestingly, If I manually access this array, console.log(locations.split("/")[i]), for any number i in the interval [0-7], I see the result I intended.
Why are the numbers 0-7 printing out when using the iterative loop, but it works exactly as intended if I use a normal index based for loop?
There's nothing wrong with your split, but you should use for..of (MDN) instead:
for (let rank of locations.split("/")) {
console.log(rank);
}
... as for..in loop iterates over indexes (and those are 0..7 for 8-element array).
As a sidenote, it's (usually) a good idea to use const (and not let) in this iteration, as variable is assigned a value once each loop (and usually shouldn't be reassigned):
for (const rank of locations.split("/")) {
console.log(rank);
}
I have the following structure, either a single string array ['stufff sjktasjtjser ((matchthis))'], or the same structure in a nested array ['stufff', ['more stuff ((matchhere))'], '((andanother))'];
I can loop and match all regex in the brackets and even replace the text:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matchs.forEach(match=>currentArrayElement=currentArrayElement.replaceAll(match[0],'whatwhat'))
console.log(currentArrayElement)//'stufff sjktasjtjser whatwhat'
//but what I actually want is
// currentArrayElement = ['stufff sjktasjtjser','whatwhat'];
Does anyone knows how I can achieve that? Or any template lib that can do that within nested arrays? I need to output sometimes an array of a string ['tss'] and sometimes an array with an object [{}].
Thanks.
The issue was that I needed to change the array in that index not the entire array.
Here is what I did then:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matches.forEach((match) => {
currentArrayElement[i] = c.split(match[0]).flatMap(
(value, index, array) => (array.length - 1 !== index
? [value, 'whatwhat',]
: value),
);
});
I have an array which I captured it from google spreadsheet.
arr = [abc#gmail.com, xyz#gmail.com, pqr123#gmail.com.....]
Every other match is giving 0. however, I have a value which is pqr123#gmail.com which is throwing result -1. I realized that it is alpha numeric and that could be the reason to not match. but again if the array element is alphanumeric it should match. what is the solution?
I am using the following code to match :-
var arr = sheet2.getRange(4,1,sheet.getLastRow(),1).getValues();
var match = arr[0].indexOf(eRecord.email) //eRecord.email is 'pqr123#gmail.com'
Logger.log(match) //current result -1
In your script, you use getRange(4,1,sheet.getLastRow(),1) of var arr = sheet2.getRange(4,1,sheet.getLastRow(),1).getValues(); as the range. In this case, the values are retrieved from a column. From this situation, I would like to propose the following modification.
From:
var match = arr[0].indexOf(eRecord.email)
To:
var match = arr.flat().indexOf(eRecord.email);
By this modification, 2 dimensional array with 1 dimensional array which has one element are flatten, and the returned value is the row index.
Reference:
flat()
I think that the problem could be in arr[0] or eRecord.email. Please, doublecheck that arr[0] is really what you need and eRecord.email contains email.
Suppose I have an Javascript array,
var example = [and, there,sharma<br, />, ok, grt]
Now I want to randomly delete some array values - but not those values which have
<br
in them, in the above example, I want to make sure
"sharma<br" is not deleted.
I also do not want to delete "/>".
Can anyone help me. I would really appreciate the answer.
First of all, that is not a valid array, unless you are missing the string quotes. Anyway, what you are searching for is Array.Filter. In your case :
var filtered = example.filter(v => v.indexOf("<br") != -1 || v.indexOf("/>") != -1)
If I have understood the problem correctly, then you want to keep those entries in the array which have substrings "<br" and "/>"
If thats the case, you can try using javascript string method includes() to see if a string contains a particular substring.
JavaScript array must be created as below
var example = ["and"," there"",sharma<br","/>","ok"," grt"];
Using splice method , to delete the array values specifying the index positions.
array splice() method changes the content of an array, adding new elements while removing old elements.
Syntax
Its syntax is as follows −
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
index −
Index at which to start changing the array.
howMany −
An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
element1, ..., elementN −
The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
var removed = arr.splice(2, 2);
This would remove your suggested output to be my assumption .
I have an assignment for a Javascript course where I have to count how many of each specific types of elements occur in an array. The array is 105 elements long, and just occurrences of the numbers 1, 2, 3, 4, and 5. I have to count how many 1's, 2's, 3's, etc.
Of course there's a simple way to do this using a loop however my teacher has added the following at the end of the assignment:
Use only the length property, toString(), sort() and indexOf() methods. Please no loops or conditional statements.
I have no idea how to do this assignment without using a loop. Any help you can give me is greatly appreciated. Thanks!
this will be the answere:
var c=[1,2,3,4,5,2,3,4,5]
c.sort()
cout_of_1 = c.indexOf(2)-c.indexOf(1);
cout_of_2 = c.indexOf(3)-c.indexOf(2);
cout_of_3 = c.indexOf(4)-c.indexOf(3);
cout_of_4 = c.indexOf(5)-c.indexOf(4);
cout_of_5 = c.length-c.indexOf(5)+1;
Since this is an assignment and you haven't really shown an attempt, I'll just give you a couple of hints.
Once you sort the array, all of the 1s will be grouped together at the start of the array, then all the 2s, etc.
The indexOf function returns the first index at which a given element can be found in the array, or -1 if it is not present.
Given the index of the first occurrence of each digit in a sorted array, you should be able to calculate how many of each digit there are. I'm not sure you'll need toString() at all. Your instructor might have thrown that in to be sneaky.
First, sort the array, then grab the first occurrence of the next value. That's the amount of numbers you have, minus the ones you already have.
var array = [1,2,5,3,2,4,5,2,1,3,3,4,5,6,2];
array = array.sort();
var ones = array.indexOf(2);
var twos = array.indexOf(3) - ones;
var threes = array.indexOf(4) - ones - twos;
...
However for the last value (5) there is no next value to check. You can work around this by checking the length and subtracting one from it.
var fives = array.length - ones - twos - threes - fours;
Keep in mind that this is actually bad code, and you should use loops.