Let's say that i got a variable which it contains the number 19. I want to make an array from it with the following numbers
var positions = [ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" ];
How is this possible in javascript?
Something like :
var number = 19;
var arr = [];
for ( i = 0; i <= number ; i++ ) {
arr.push(i < 10 ? ("0" + i.toString()) : i.toString());
}
demo : http://jsfiddle.net/Kfnnr/1/
Alternatively:
var mynumber = 19,
myarr = String(Array(mynumber+1))
.split(',')
.map(function(el,i){return i<10 ? '0'+i : ''+i;});
For zeropadding you may want to use:
function padLeft(nr,base,chr){
base = base || 10;
chr = chr || '0';
var len = (String(base).length - String(nr).length)+1;
return len > 0? Array(len).join(chr)+nr : nr;
}
// usage
padLeft(1); //=> '01'
padLeft(1,100); //=> '001'
padLeft(1,10000,'-'); //=> '----1'
Update 2019: in es20xx String.prototype contains a native padStart method:
"1".padStart(2, "0"); //=> "01"
// ^ max length
// ^ fill string (or space if omitted)
essentially you want to pad 0's and the answers here will not suffice and scale when the number is changed.. Probably the better solution would be
function padZero(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Using this example finally solved my own ##iterator function interface issue;
Thanks a lot
var myArray = [];
function getInterval (start, step, end, ommit){
for (start; start <= end; start += step) {
myArray.push( start < 10 ? ("" + start.toString()) : start.toString());
}
}
getInterval(2, 2, 20, 20);
myArray; // __proto__: Array
// (10) ["2", "4", "6", "8", "10", "12", "14", "16", "18", "20"]
myArray[4]; // "10"
Related
I have a problem where i must take an array of strings(some numbers and some letters)and remove the Zeros, move them to the end, and return the array. The final result needs all of the numbers to be integers in the string.
I have tried mapping the array and parsing the integers. This works unless the array passed in has letters. then all the letters are relaced with NaN. I cant seem to set up a conditional that will only operate on the integers.
var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];
but it should be
var final = ["a","b","c","d",1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]
I need to parse the integers but cant get map to do it without the problem i described earlier. I also tried using if statements too, with no help.
You could convert all numbers or try to convert and take the value, if the conversion is falsy.
var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log(final.map(v => +v || v));
Zero safe approach.
var final = ["a", "b", "c", "d", "1", "1", "3", "1", "9", "9", "0", 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log(final.map(v => isNaN(v) ? v : +v));
You can try with isNaN() and Array.prototype.map() along with Conditional (ternary) operator:
var final = ["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0];
final = final.map(i => isNaN(i) ? i : Number(i));
console.log(final);
You want to parse the number but return the original element if it's NaN using a conditional:
var final = array.map((x) => {
var n = parseInt(x, 10);
return !isNaN(n) ? x : n;
})
You could use this:
var input = ["0", "a", "0", "b", "0", "0", "c", "d", "0", 0, "0", "1", "0", "1","3","0", "1","9","9", "0"];
var final = [...input.filter(s => s != 0),
...input.filter(s => s == 0)
].map(s => isNaN(s) ? s : +s);
console.log(final);
Using map() and validating on isNaN().
["a","b","c","d","1","1","3","1","9","9",0,0,0,0,0,0,0,0,0,0]
.map(x => !isNaN(x) ? Number(x) : x)
I am creating a Google App Script and inside I am trying to create a table structure where the cell data is the value of the row heading + the value of the column heading.
I have the following Headings that represent the day and hour...
var tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"]
var tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
I want the contents to be equal to "M0", "M1", "M2", ..., "TH1", ..., etc. So the number of columns is 7 and the number of rows is 10.
I was doing some research into how to do this and found Array Comprehensions, but I quickly found out that those are now NOT supported and we should not use them.
var table = [for (day of tableHeadings) [for (hour of tableHours) day + hour]];
FYI, I don't know if I need to swap the 2 for-clauses yet. I am representing the columns as the days of the week. Also, I don't know if this works on m x n arrays as Google App Script does not allow for this syntax, but if you scroll down to Array comprehensions with two arrays to see an example I used as inspiration.
In most of the documentation, I have been able to find how to convert a single-array Array Comprehension to use maps and filter, but I have not found anything on how to convert a double-array (m x n) Array Comprehension. Some documentation talks about double-array (m x m) Array Comprehension but does not discuss how to convert them.
Is there a simple way to convert a double-array (m x n) Array Comprehension? Just to be very specific, the solution NEEDS to work for (m x n) arrays.
You can achieve this with nested Array#map calls:
var tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"];
var tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var result = tableHeadings.map(function(day) {
return tableHours.map(function(hours) {
return day + hours;
});
});
console.log(result);
And using ES6 arrow functions you can have a one liner:
const tableHeadings = ["M", "T", "W", "TH", "F", "S", "SU"];
const tableHours = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
const result = tableHeadings.map((day) => tableHours.map((hours) => day + hours));
console.log(result);
if I have a js array like below, is there a simple way to re-group the array values by range, the logic is based on the range step, the range step is 1, so if the array values are continuous increased by 1, then it should be write like "1-3", otherwise it should be break to another group, thanks a lot!
var list = ["1", "2", "3", "5", "6", "9", "12", "13", "14", "15", "16"]
function(list) {
// * some function here //
return ["1-3", "5-6", "9", "12-16"]
}
You could use Array#reduce for it.
var array = ["1", "2", "3", "5", "6", "9", "12", "13", "14", "15", "16"],
result = array.reduce(function (r, a, i, aa) {
r.push(!i || aa[i - 1] - a + 1 ? a : r.pop().split('-')[0] + '-' + a);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here is not as compact as #nina-scholz's version, but 70% faster.
It also allows creating only "non-redundant" ranges (ranges with minimum difference of 2 or greater, which might speed up decoding)
function getRanges(array, minRange, sort)
{
if (sort)
array = new Float64Array(array).sort();
let min = array[0],
max = min,
result = [];
minRange = minRange ? 1 : 0;
for(let i = 1, c = array.length + 1; i < c; i++)
{
const id = array[i];
if (max == id - 1)
{
max = id + ""; // + converting to string
continue;
}
if (max-min > minRange)
result.push(min + "-" + max);
else if (min != max)
result.push(min, max);
else
result.push(min);
min = max = id + ""; // + converting to string
}
return result;
}
//examples
var array = ["1", "2", "3", "5", "6", "9", "12", "13", "14", "15", "16"];
console.log(JSON.stringify(array));
console.log("ranges with minimum diference of 1:", JSON.stringify(getRanges(array)));
console.log("ranges with minimum diference of 2:", JSON.stringify(getRanges(array, true)));
array.sort(()=>.5-Math.random());//randomize array
console.log(JSON.stringify(array));
console.log("ranges with minimum diference of 1 sorted:", JSON.stringify(getRanges(array, false, true)));
console.log("ranges with minimum diference of 2 sorted:", JSON.stringify(getRanges(array, true, true)));
console.log("ranges with minimum diference of 1 unsorted:", JSON.stringify(getRanges(array)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
While trying to get all permutations using Heap's algorithm, I met trouble storing the results in array.
The result generated is (from console.log(arr);)
["1", "2", "3"]
["2", "1", "3"]
["3", "1", "2"]
["1", "3", "2"]
["2", "3", "1"]
["3", "2", "1"]
but only the last value is stored in the arr, and the array stored somehow is this (from console.log(JSON.stringify(allPermutations)); )
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
var allPermutations = [];
function swap(arr,index1,index2){
var dummy = arr[index1];
arr[index1] = arr[index2];
arr[index2] = dummy;
return arr;
}
function generate(n,arr){
if(n==1){
console.log(arr);
//result:
//["1", "2", "3"]
//["2", "1", "3"]
//["3", "1", "2"]
//["1", "3", "2"]
//["2", "3", "1"]
//["3", "2", "1"]
allPermutations.push(arr);
}else{
for(var i=0;i<n-1;i++){
generate(n-1,arr);
if( n%2 ==0){
arr = swap(arr,i,n-1);
}else{
arr = swap(arr,0,n-1);
}
}
generate(n - 1, arr);
}
}
generate(3,['1','2','3']);
console.log(JSON.stringify(allPermutations));
/*result:
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]*/
What's wrong with this? Would love to understand. Thanks
Replace allPermutations.push(arr) with allPermutations.push(arr.slice()).
The problem is, you keep pushing the same array, then changing that array. When you push an array, you don't push a copy of it: you push a reference. There is only one array, and six references to it; when you read them out, they all read the same, because they are all the same array.
.slice() will give you a new array with the same elements; this way, you get six new arrays into your result, instead of six mentions of the same array.
From one of my earlier answers that is almost-but-not-quite a duplicate, a metaphor I like for this:
As a metaphor, imagine a theatre director in casting. He turns to an actor, says "You... you'll be Romeo.". Then he looks at the same actor, says "You... you'll be Mercutio. Here, Mercutio, take this sword. Romeo... who told you to get a sword?!?" completely failing to realise that, if Romeo and Mercutio are the same person, if one of them picks up a sword, the other does it too.
That's because arrays are objects, and objects are passed by value, but that value is a reference.
Then, your code keeps pushing the same arr reference to allPermutations. But the values in that reference are modified later.
Instead, you should push a copy of the array. You can copy it with .slice().
var allPermutations = [];
function swap(arr, index1, index2) {
var dummy = arr[index1];
arr[index1] = arr[index2];
arr[index2] = dummy;
return arr;
}
function generate(n, arr) {
if (n == 1) {
allPermutations.push(arr.slice());
} else {
for (var i = 0; i < n - 1; i++) {
generate(n - 1, arr);
if (n % 2 == 0) {
arr = swap(arr, i, n - 1);
} else {
arr = swap(arr, 0, n - 1);
}
}
generate(n - 1, arr);
}
}
generate(3, ['1', '2', '3']);
document.write(JSON.stringify(allPermutations));
I have a problem with for loop...
i have an array with string date
var eru = [
[" 1 Gennaio-7 Gennaio 2014", 17],
[" 8 Gennaio-14 Gennaio 2014", 14],
[" 15 Gennaio-21 Gennaio 2014", 16],
[" 22 Gennaio-28 Gennaio 2014", 16],
[" 29 Gennaio-4 Febbraio 2014", 15],
[" 5 Febbraio-11 Febbraio 2014", 19]
]
i push in empty array year, day and month of string, but...
in the array i have a name of month, but i want a number utc of month. I have a for loop into first for loop when i replace name of month with number and push new variable in empty array. But the variable pushed is undefined and i don't understand the cause...
This is jsfiddle
http://jsfiddle.net/hd5z9rhd/
var higheru = [];
var search = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'];
var replace = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"];
var anno;
var mese;
var giorno;
for (var i = 0; i < eru.length; i++) {
var parsa = eru[i];
var primo = parsa[0] + "";
var secondo = parsa[1];
anno = primo.substr(-4);
giorno = primo;
var valoreday = giorno.search("-");
var balle = giorno.substr(1, valoreday);
var trova = balle.search(" ");
giorno = balle.substr(0, trova);
mese = balle.substr(trova, valoreday);
mese = mese.replace("-", "");
for (s = 0; s < search.length; s++) {
var corrispondenza = search[s];
if (mese == corrispondenza) {
var newmese = mese.replace(search[s], replace[s]);
}
}
higheru.push([anno, newmese, giorno, secondo]);
}
Here :
...
mese = balle.substr(trova, valoreday);
mese = mese.replace("-", "");
var newmese = '';
for (s = 0; s < search.length; s++) {
var corrispondenza = search[s];
if (mese.trim() == corrispondenza.trim()) { // <- Remove space with trim()
newmese = mese.replace(search[s], replace[s]);
break;
}
}