How would i use javascript or jquery to add a leading zero to this?
for (im=1;im<=31;im++){
days[im]=everyDay[im];
}
Consider:
for (var t, im=1; im<=31; im++){
t = everyDay[im];
days[im] = (t < 10? 0 : '') + t;
}
Prepend it with a 0, and then take the last two characters:
var days = {};
for (im=1;im<=31;im++){
days[im] = ('0' + im).substr(-2);
}
for (im=1;im<=31;im++){
days[im] = (everyDay[im] < 10 ? '0' : '') + everyDay[im];
}
If you want leading zeros in your days array. You can create another array with days as strings like this, and use one or the other where it belongs or use parseInt() on the new array:
var days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
strDays = [];
for (var i = 0, l = days.length; i < l; i++) {
strDays.push(String(days[i]).length < 2 ? '0' + days[i] : String(days[i]));
}
// `strDays` prints: ["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"]
EDIT:
Even shorter:
var strDays = [];
for (var i = 1; i < 32; i++) {
strDays.push(('' + i).length < 2 ? '0' + i : '' + i);
}
for (var im=1;im<=31;im++){
var x = parseInt(everyDay[im]);
if(x < 10)
days[im]='0' + x;
else days[im]= x;
}
Related
My goal is the following:
Create a loop that compares the array of numbers provided, for the number 28.
Log over, if it is greater than 28, and under if it is less than 28.
Don't log anything if it is equal to 28.
Expected output:
2 is under
40 is over
31 is over
This is my code currently; I feel like I am so close, but I'm not sure.
var rando_array = [2, 40, 31, 29, 9, 12, 41, 90];
rando_array.sort();
for (var i = 0; i < var rando_array.length; i++) {
var Its;
if (i > 28) {
Its = "over";
} else if (i < 28) {
Its = "under";
}
console.log(rando_array[i] + "Its");
};
Since you wanted to loop though the array, this solution uses a for-loop.
The same result could be achieved using forEach , maps etc...
let rando_array = [2, 40, 31, 29, 9, 12, 41, 90];
for (var i = 0; i < rando_array.length; i++) {
if (rando_array[i] > 28) {
console.log(rando_array[i] + " is over")
} else if (rando_array[i] === 28) {
// Do nothing
/* Uncomment to log eqaul
console.log(rando_array[i] + " is equal")
*/
} else {
console.log(rando_array[i] + " is under")
}
};
let arr = [2, 40, 31, 29, 9, 12, 41, 90]
const max_value = 28
arr.filter(item => item > max_value).forEach(number => {
// console logs if num is greater than 28
console.log(number)
})
I try to receive only even numbers, summing values from two arrays. If the result cannot be even, it should return one even value without summing being executed.
These are two arrays:
var a = [-2, 10, 30, 50, 11, 22, 100];
var b = [10, 8, 22, 5, 11, -5];
So, the result should be :
[8, 18, 52, 50, 22, 22, 100],
which stems from the following:
-2 + 10 = 8 (even), 10 + 8 = 18 (even),
30 + 22 (even), 50 + 5 = 55 (not even),
so 50 should be, because it is even, 11 + 11 = 22 (even), 22 + (-5) = 17 (not even), so 22 should be, because it is even, 100 is even.
I have the code, but it returns boolean "true" instead of 50 and second 22. How that can be fixed?
function sumArray(a, b) {
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
c.push((a[i] || 0) + (b[i] || 0));
}
return c;
}
var a = [-2, 10, 30, 50, 11, 22, 100];
var b = [10, 8, 22, 5, 11, -5];
var numbers = sumArray(a, b);
function OnlyEvens(numbers) {
;
var evens = [];
for(var i = 0; i < numbers.length; i++){
if(numbers[i]%2 == 0) evens.push(numbers[i]);
else (evens.push (a[i] % 2 == 0 || b[i] % 2 == 0))
}
return evens
}
var check = OnlyEvens(numbers);
console.log(check)
When you tried to push the array a number in case it's not even, you actually pushed the result of the condition which will give you a boolean result true/false.
a[i] % 2 == 0|| b[i] % 2 == 0
What you can possibly do is add a ternary condition. if a[i] is even, then push that value to the array. else, push b[i] (since it must be even because uneven + uneven gives you an even number, hence it will enter the
a[i] + b[i] % 2 === 0
condition on the first if.
function sumArray(a, b) {
var c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
c.push((a[i] || 0) + (b[i] || 0));
}
return c;
}
var a = [-2, 10, 30, 50, 11, 22, 100];
var b = [10, 8, 22, 5, 11, -5];
var numbers = sumArray(a, b);
function OnlyEvens(numbers) {
;
var evens = [];
for(var i = 0; i < numbers.length; i++){
if(numbers[i]%2 == 0) evens.push(numbers[i]);
else (evens.push (a[i] % 2 == 0 ? a[i] : b[i] ))
}
return evens
}
var check = OnlyEvens(numbers);
console.log(check)
You could check the remainder and get either both values or just a single one.
function sumEven(a, b) {
return a.map((v, i) =>
v % 2 === b[i] % 2
? v + b[i]
: v % 2
? b[i]
: v
);
}
const
a = [-2, 10, 30, 50, 11, 22, 100],
b = [10, 8, 22, 5, 11, -5];
console.log(...sumEven(a, b));
Another approach with finding the value.
function sumEven(a, b) {
return a.map((v, i) => [v + b[i], v, b[i]].find(v => v % 2 === 0));
}
const
a = [-2, 10, 30, 50, 11, 22, 100],
b = [10, 8, 22, 5, 11, -5];
console.log(...sumEven(a, b));
You could recurse over the values of both arrays ( a and b ) and add the even total or even value to the new array. After that add the leftover values to the result ( assumed they can be both odd or even in the code below ).
var a = [-2, 10, 30, 50, 11, 22, 100];
var b = [10, 8, 22, 5, 11, -5];
let c = [];
while( a.length > 0 && b.length> 0 ) {
let val_1 = a.shift();
let val_2 = b.shift();
let total = val_1 + val_2;
if( is_even(total) )
c.push( total );
else if ( is_even(val_2) )
c.push( val_2 );
else if ( is_even(val_1) ) // unnecessary check
c.push( val_1 );
}
// add leftover values (always)
c = c.concat(a).concat(b);
console.log(c);
function is_even( integer ) {
return integer % 2 === 0;
}
How would one push multiples of a number to an array? For example, if the input is (6), I want to create an array that holds [6, 12, 18, 24, 30, 36, etc...]
The most intuitive method to me does not work.
for (var i = 0; i < 10; i++) {
firstArray.push(arr[0] *= 2);
}
This multiplies the number that comes before it by 2, causing an exponential growth. [14, 28, 56, 112, 224, 448, 896, 1792, etc.]
How would one achieve this?
Problem:
The problem in the code, as commented by Pranav is the use of multiplication by two in the for loop.
Using i iterator index can solve the problem.
firstArray.push(6 * (i + 1));
As i is starting from 0, i + 1 will give the number which is 1-based.
Another Approach:
First add the number
var num = 6,
arr = [num];
Then add the number which is double of the previous in the array.
for (var i = 1; i < 10; i++) {
arr.push(arr[i - 1] + num);
}
var arr = [6];
for (var i = 1; i < 10; i++) {
arr.push(arr[i - 1] + arr[0]);
}
console.log(arr);
The same thing can also be done in single line using for loop.
var arr = [];
for (let i = 0, num = 6; i < 10; i++, num += 6) {
arr.push(num);
}
console.log(arr);
You can use map:
function multiplyArrayElement(num) {
return num * 2;
}
numbers = [6, 12, 18, 24, 30, 36];
newArray = numbers.map(multiplyArrayElement);
https://jsfiddle.net/25c4ff6y/
It's cleaner to use Array.from. Just beware of its browser support.
Array.from({length: 10},(v,i) => (i + 1) * 6)
try this one
for (var i = 0; i < 10; i++) {
firstArray.push(arr[0] * (i+1));
}
var arr = [];
var x = 6; //Your desired input number
var z;
for(var i=1;i<10;i++){
z = (x*i);
arr.push(z);
}
console.log(arr);
"One line" solution with Array.fill and Array.map functions:
var num = 6;
var arr = new Array(10).fill(0).map(function(v, k){ return num *(k + 1); });
console.log(arr); // [6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
Here is my dilemma, I have this code:
var fibs = [1, 2];
for (i = 0; i < (window.innerWidth / 50); i++) {
if (fibs.length < 15) {
var n = fibs[i] + fibs[i + 1];
fibs.push(n);
}
}
Which creates an array of the Fibonacci Sequence. I then copy the contents of fibs to a new array, top. What I'm having trouble with is that I need every 2nd and 3rd elements on top to be the inverse sign of fibs. ie. top[0] = fibs[0]; top[1] = -fibs[1]; top[2] = -fibs[2]; top[3] = fibs[3] I want to be able to do this programmatically because the lengths of the arrays will change based on the width of the screen.
Below is what I'm trying to use.
var top = [];
for (i = 0; i < fibs.length; i++) {
if (i % 2 == 0 || i % 3 == 0) {
top[i] = -(fibs[i]);
} else {
top[i] = fibs[i];
}
}
What I get is [-1, 2,-3, -5, -8, 13, -21, 34, -55, -89, -144, 233, -377, 610, -987], when what I'm looking for is [-1, 2, 3, -5, -8, 13, 21, -34, -55, 89, 144, ... ].
While this might not be the best way to do it, this ought to work:
var topp = [];
for (i = 0; i < fibs.length; i++) {
if (i % 3 == 1 || i % 3 == 2) {
topp[i] = fibs[i] - (2 * fibs[i]);
} else {
topp[i] = fibs[i];
}
}
The code is pretty self explanatory.
EDIT:
Thanks to #alexpods for the tip about the top keyword.
Thanks to #Scott Hunter for pointing out the logical error.
Allow me to throw in a bit more flexible (and readable) solution to your problem:
function fibonacci(length) {
var out = [0, 1];
for (i = 2; i < length; i++) {
out[i] = out[i-1] + out[i-2];
}
return out;
}
function modifyValues(source, factors) {
var out = [];
for (i = 0; i < source.length; i++) {
out[i] = source[i] * factors[i % factors.length];
}
return out;
}
fibs = fibonacci(15);
mod1 = modifyValues(fibs, [1,-1,-1]);
console.log(fibs, mod1);
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
[0, -1, -1, 2, -3, -5, 8, -13, -21, 34, -55, -89, 144, -233, -377]
I believe you want
if ( i%3==1 || i%3==2 ) {
Alternatively, you could use
if ( i%3 ) { // will be treated as true as long as i%3 != 0
I have a very large array of objects — around 30000.
randomStart = Math.floor( Math.random() * arr.length )
I'm selecting a random range from the total length.
what I want to do is loop through the array beginning at randomStart and ending at randomStart + n.
Note:
This array must stay intact, because it's too computationally expensive to re-render the entire set.
What's the best way to go about this ? What looping paradigm should be used : for, while, etc
Instead of setting var i = 0 at the beginning of your for loop, simply set it to your starting index, then instead of setting the stopping condition to i < array.length, set it to i < ending_index.
This works because you then iterate i through all indexes between the start and end_index, just like in a "normal" for loop you iterate from 0 to the end of the array.
If you are trying to process the array in batches try this. You will have to adjust the batch limit based on your preference.
function ProcessLargeArray() {
var largeArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];
var batchLimit = 10;
for (var startIndex = 0; startIndex < largeArray.length; startIndex = startIndex + batchLimit) {
ProcessBatch(largeArray, startIndex, GetEndIndex(startIndex, batchLimit, largeArray.length));
}
}
function GetEndIndex(startIndex, batchLimit, arrayLength) {
var endIndex = startIndex + batchLimit;
if (endIndex > arrayLength) {
return arrayLength;
}
return endIndex;
}
function ProcessBatch(someArray, startIndex, endIndex) {
console.log("Start Batch from " + startIndex + " to " + endIndex);
for (var i = startIndex; i < endIndex; i++) {
console.log(someArray[i]);
}
console.log("Ending Batch from " + startIndex + " to " + endIndex);
}
var arr = [1,2,3,4];
var batchSize = 2;
var randomStart = Math.floor(Math.random() * (arr.length - batchSize));
for (var i = randomStart; i < randomStart + batchSize ; i++) {
///Code here
}