this is my code currently:
let array = [`1 (1).jgp`,`1 (2).jgp`,`1 (3).jgp`,`1 (4).jgp`,`1 (5).jgp`,`1 (6).jgp`,`1 (7).jgp`,`1 (8).jgp`,`1 (9).jgp`,`1 (10).jgp`,`1 (11).jgp`]
//rest of the code
Is there a more efficent way of storing the data?
I have tried:
for (i = 0; i < 12; i++) {
let array = [`1`+(i)+`.jgp`]
};
//rest of the code
But, then when I tried to call array it returned:
Uncaught ReferenceError: array is not defined
at :1:1
I also tried:
let array = [`1`+(i = 0; i < 12; i++)+`.jgp`]
//rest of the code
But that returned: Uncaught SyntaxError: Unexpected token ;
Please let me know what I'm doing wrong? Or how I can make this code more efficient.
Thanks,
You can generate the array using Array#from:
const arr = Array.from({ length: 10 }, (_, i) => `1 (${i + 1}).jgp`);
console.log(arr);
Although a simple for loop would work as well:
const array = []; // declare an empty array
for (let i = 1; i <= 10; i++) {
array.push(`1 (${i}).jgp`); // push each item to the array
};
console.log(array);
Is there a more efficent way of storing the data?
You mean store in such a way that less storage is required?
Store in this format
var arrayObj = {
template : "{{i}} ({{i}}).jgp",
startIndex : 1,
endIndex : 10
};
Or how I can make this code more efficient.
If how much storage is used is not the concern, then simply use a simple iterator
var array = [];
for( var counter = 1; counter <= 10; counter++ )
{
array.push( "1 ( " + counter + " ).jgp" );
}
You can do
let array = [];
for (let i = 0; i < 12; i++) {
array.push(`1 (`+i+`).jgp`);
};
console.log(array);
Related
I am attempting to create a matrix of 3 arrays with 10 elements in each array. Each element should be a random number between 1 and 10. I wanted to use a single function to generate each of the arrays, and used this:
var array1 = [];
var array2 = [];
var array3 = [];
var tempName;
function fcnArrayGenerate(){
let i = 1;
while (i < 4){
tempName = "array" + i;
let j = 0;
while (j < 10){
tempName.push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(array1);
console.log(array2);
console.log(array3);
}
However, when I run the function, I receive an error stating that "tempName.push is not a function." Any assistance on how to correct this would be appreciated. Thank you.
Instead of using three variables for three different arrays, you can use a single multidimensional array to store those three arrays.
let array = [[], [], []];
function fcnArrayGenerate() {
let i = 0;
while (i <= 2) {
let j = 0;
while (j < 10) {
array[i].push(Math.floor(Math.random() * 10) + 1);
j++;
}
i++;
}
}
// call the function
fcnArrayGenerate();
// now print the arrays as tables
console.table(array);
console.table(array[0]);
console.table(array[1]);
console.table(array[2]);
Note: console.table() allows you to print out arrays and objects to the console in tabular form.
If you want to push into tempName you have to initialise it with an empty array first. Right now it’s undefined. Hence you’re seeing the error as you can’t push something to undefined
Do this:
var tempName = []
To make variable names incremental, you can pass them as objects.
var data = {
array1: [],
array2: [],
array3: []
}
function fcnArrayGenerate(){
let i = 1;
while (i < 4){
let j = 0;
while (j < 10){
data['array' + i].push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(data.array1);
console.log(data.array2);
console.log(data.array3);
}
fcnArrayGenerate();
Newer to coding and javascript and I am trying a codewars challenge. I setup an array to repeat a letter at certain indexes of my newArray based on a loop. For example if input was: cwAt expected output should be: C-Ww-Aaa-Tttt.
Been stuck on this for several hours (and have slept on it). I get error code:
newArray.join is not a function
when I try to run this and not sure what I can do to fix this problem. I feel its something simple and I just need to learn why this is happening.
function accum(s) {
let mumble = s.split('');
for (i = 0; i < mumble.length; i++) {
let newArray = [mumble[i].toUpperCase(), ''];
for (j = i; j > 0; j--) {
newArray = newArray.push(mumble[i]);
};
// Merge the new array into a string and set it at the mumble index required
mumble[i] = newArray.join('');
};
//Return new mumble with - as spaces between elements
return mumble.join('-');
}
console.log(accum('cwAt'));
Change newArray = newArray.push(mumble[i]); to newArray.push(mumble[i]);
push returns new length of the array.
You are storing a number in newArray. Try replace the 4 line with:
let newArray[i] = [mumble[i].toUpperCase(), ''];
and the 5 line :
for (j = 0; j < 0; j++) {
and the 6:
newArray[j] = newArray.push(mumble[i]);
I am trying to combine a string and number to a dynamiclly generated variable.
Currently tried it this way:
const ElementCount = 2;
for (i = 1, i <= ElementCount, i++) {
let SampleVariable[i] = "test";
}
ElementCount will later on be dynamic.
The result of the above function should look like this:
SampleVariable1 = "test"
SampleVariable2 = "test"
My code seems to be wrong - what do I have to change here?
Solution can be native JS or jQuery as well.
Thanks a lot!
solution is to use eval, but It's nasty code, Avoid using 'eval', just use an array or object.
1, eval solution:
const ElementCount = 2;
for (let i = 1; i <= ElementCount; i++) {
eval("let SampleVariable[" + i + "] = 'test'");
}
2, array solution:
const ElementCount = 2;
let Variables = []
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}
3, object solution:
const ElementCount = 2;
let Variables = {}
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}
There are few mistakes in your code
You using comma , to separate the statements. You should use semicolon ;
You are declaring SampleVariable inside the for loop so its not avaliable outside. Declare it outside the loop.
You shouldn't use independent variable for this purpose as they just differ by 1. You should store them in array and use SampleVariable[number] to access them.
You should initialize i = 0 otherwise the first element of SampleVariable will be undefined
const ElementCount = 2;
let SampleVariable = [];
for (let i = 0; i < ElementCount; i++) {
SampleVariable[i] = "test";
}
console.log(SampleVariable);
This is my solution
const ElementCount = 2;
for(i = 1; i <= ElementCount; i++) {
this['SampleVariable'+i] = "test";
}
SampleVariable1 // "test" (browser)
this.SampleVariable2 // "test"
hello I would like to build an array that every element will be a pair of objects , Something like this
var Shelves = new arr[][]
var books = new Books[] ;
Shelves[book[i],book[j=i+1]],[book[i+1],book[j=i+1]] and so on......;
I mean that I understand how to go with a for loop and to get the elements 'but how to push them in pairs array? arr.push doesn't work :(
build1ArrPairs(1Arr) {
if (1Arr != undefined || 1Arr!=null) {
for (var i = 0; i < 1Arr.length; i = i + 1) {
for (var j = i + 1; j <= 1Arr.length; j++) {
this.1ArrPair.push(1Arr[i] 1Arr[j]);
break;
}
}
}
}
Thanks :)
Alternatively, you can use array#reduce to group your array.
var names = ['a', 'b','c','d','e'];
var result = names.reduce((r,w,i) => {
let index = Math.floor(i/2);
if(!Array.isArray(r[index]))
r[index] = [];
r[index].push(w);
return r;
},[]);
console.log(result);
First of all, variables names can't start with a number.
Second, initialize an array, then add your elements - two at a time - and return the array:
var ans = [];
if (Arr != undefined || Arr != null) {
for (var i=0; i<(Arr.length-1); i+=2) { // Note the loop stops 2 elements before the last one
ans.push([Arr[i], Arr[i+1]]);
// ^ Note the comma - it's missing in your code
}
}
return ans;
Similar to this question - Array value count javascript
How would I go about doing this, except with dynamic values?
var counts = []
var dates= [ "28/05/2013", "27/05/2013", "28/05/2013", "26/05/2013", "28/05/2013" ];
How would I get a count of the duplicated array values? So how many 28/05/2013 etc. The dates are all dynamic, so I can't just search for set values. I just can't get my head around how I would do this.
I may just scrap this idea, and get the value count from the last 10 days or something... but this may come in handy later(if it is even possible to do this).
This will do it:
var counts = {};
for (var i=0; i<dates.length; i++)
if (dates[i] in counts)
counts[dates[i]]++;
else
counts[dates[i]] = 1;
The result will be
> counts
{
"28/05/2013": 3,
"27/05/2013": 1,
"26/05/2013": 1
}
Make counts an object to perform duplicate detection in constant time.
var counts = {}
for (var i = 0; i < dates.length; i++) {
var date = dates[i];
if (counts[date] === undefined) {
counts[date] = 0;
}
counts[date] += 1;
}
console.log(counts);
Try like this
Updated
var dates= [ "28/05/2013", "27/05/2013", "28/05/2013", "26/05/2013", "28/05/2013" ];
var findStr = "28/05/2013";
var indexs = dates.indexOf(findStr,0),count=0;
for (var i=0;i< dates.length;i++){
if (indexs >= 0){
indexs = dates.indexOf(findStr,indexs + 1);
count++;
}
}
alert(count);
See Demo