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]
Related
I am new to Javascript and at the moment I'm learning how "arrays" are used.
In my code below I have 12 numbers held by an array variable. Next, the for loop is iterating over the indexes to check which values have 2 or more digits, the while-loop then summarizes the digits (e.g. value '130' at index 8, will be 1+3+0=4).
Final step..and also where I'm stuck:
I need to sum up all the "new" index values and return the result in a variable.
With the numbers provided in the code, the result would be '50'.
Anyone have clue on how to do this? I've tried the conventional for-loop with sum += array[i], but it doesn't work.
var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];
for (var i = 0; i < arrChars.length; i++) {
var digsum = 0;
while (arrChars[i] > 0) {
digsum += arrChars[i] % 10;
arrChars[i] = Math.floor(arrChars[i] / 10);
}
var sum = 0; // this last part won't work and I just get "nan", 12 times
for (var j = 0; j < arrChars.length; j++) {
sum += parseInt(digsum[j]);
}
console.log(sum); // desired output should be '50'
}
Move digsum outside and it will contain the sum of every number in it:
var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];
var digsum = 0;
for (var i = 0; i < arrChars.length; i++) {
while (arrChars[i] > 0) {
digsum += arrChars[i] % 10;
arrChars[i] = Math.floor(arrChars[i] / 10);
}
}
console.log(digsum); // desired output should be '50'
I'd make this easy and just flatten the array of numbers into a string of digits, split that into an array of single digits, and add them together:
var arrChars = [4, 2, 14, 9, 0, 8, 2, 4, 130, 65, 0, 1];
console.log([...arrChars.join('')].reduce((agg, cur) => agg += +cur, 0));
Hi I have this example where I want my 1D array to be a 2D array 4x3
var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
var i, j, t;
var positionarray1 = 0;
var array2 = new Array(4);
for (t = 0; t < 4; t++) {
array2[t] = new Array(3);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
array2[i][j] = array1[i];
array2[i][j] = array1[j];
}
positionarray1 = positionarray1 + 1; //I do this to know which value we are taking
}
console.log(array2);
My solution is only giving me the first numbers of the array1. Any idea?
i and j are indexes into the new 2D array that only run up to 0 to 3 and 0 to 2, which is why you are seeing the beginning values over and over. You need a way to index array1 that goes from 0 to 11.
It looks like you are on the right track with "positionarray1" and "position", though you need to move where you are incrementing it. You need to use that value when indexing array1 rather than i and j:
array2[i][j] = array1[positionarray1];
array2[i][j] = array1[positionarray1];
positionarray1++;
If you rename i to row and j to col, it makes is easier to see what is going on. Also, avoid magic numbers. I am seeing 3 and 4 all over the place. These can be replaced with parameter references. All you need to do it wrap your logic within a reusable function (as seen in the reshape function below).
The main algorithm is:
result[row][col] = arr[row * cols + col];
There is no need to track position, because it can be calculated from the current row and column.
const reshape = (arr, rows, cols) => {
const result = new Array(rows);
for (let row = 0; row < rows; row++) {
result[row] = new Array(cols);
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
result[row][col] = arr[row * cols + col];
}
}
return result;
};
const array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
const array2 = reshape(array1, 4, 3);
console.log(JSON.stringify(array2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
var i, j, t;
var positionarray1 = 0;
var array2 = new Array(4);
for (t = 0; t < 4; t++) {
array2[t] = new Array(3);
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 3; j++) {
array2[i][j] = array1[i*3+j]; //here was the error
}
positionarray1 = positionarray1 + 1; //I do this to know which value we are taking
}
console.log(array2);
I just solved it thanks for your comments. I actually used one apportation, but it was 3 instead of 2.
solution with 1 loop for efficiency :
const arr1D = new Array(19).fill(undefined).map((_, i) => i);
const arr2D = [];
const cols = 3;
for (let i = 0, len = arr1D.length; i < len; ++i) {
const col = i % cols;
const row = Math.floor(i / cols);
if (!arr2D[row]) arr2D[row] = []; // create an array if not exist
arr2D[row][col] = arr1D[i];
}
console.log({ arr1D, arr2D });
I have an arrays of numbers, and specified range if sequence continues (range rule was met between two numbers) then i add value to result and increase counter by one, else i reset the counter and add nothing to result on this step. Better show in an example:
const numbers = [1, 4, 5, 6, 7, 33, 44, 46]; // they are always going to be from smallest to bigger
const progress = [0, 10, 20, 30, 40, 50, 60]; // 70, 80, etc
let res = 0;
for (let i = 1, j = 0; i < numbers.length; i++) {
const range = numbers[i] - numbers[i - 1];
if (range <= 5) {
j += 1;
res += progress[j];
} else {
j = 0;
}
}
res; // 110
Is there better way to approach this problem?
Well, by looking at your code & the explanation you gave, I think you have incremented 'j' before you added progress for 'j'. that portion should be like following...
if (range <= 5) {
res += progress[j];
j += 1;
}
You have asked for a better approach. But it would help if you specified from which perspective/scenario you are looking for a better approach.
you can do the same with reduce method
const numbers = [1, 4, 5, 6, 7, 33, 44, 46]; // they are always going to be from smallest to bigger
const progress = [0, 10, 20, 30, 40, 50, 60]; // 70, 80, etc
let resp = 0;
const result = numbers.reduce((acc, rec, i, arr) => {
if (rec - arr[i - 1] <= 5) {
resp += 1;
acc = acc + progress[resp];
return acc;
}
resp = 0;
return acc;
}, 0);
result;
You can read more about reduce here
Hope it answers your question.
Happy coding!
I have created an Array with some numbers.
I want to find out how many even, and how many odd numbers it is in
this Array. I have to print it out like this: (this is just an example)
Even number: 6
Odd number: 7
I need to make a loop that count up how many it is off even and odd numbers.
This is what I have so far
<script>
window.onload = run;
var tall = [5,10,15,20,25,30,35,40,45,50];
function run() {
tall = [5,10,15,20,25,30,35,40,45,50];
liste(tall);
}
function liste(arr) {
var sumOdd = 0; // Odd 1, 3, 5 etc..
var sumPar = 0; // Even 2, 4, 6 etc..
for(var i = 0; i < arr.length; i++) {
if(arr[i] % 2 === 0) {
sumPar += arr.length;
}
else {
sumOdd += arr.length;
} // Even numbers // Odd numbers
document.getElementById("print").innerHTML = "Partall: " + sumPar + "<br />" + "Oddetall: " + sumOdd;
}
}
}
</script>
Its something that is wrong here, and I dont know what.
You could iterate with Array#reduce and count only the odds. For the rest just take the difference of the length of the array and the odds.
var tall = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
odd = tall.reduce(function (r, a) { return r + a % 2; }, 0),
even = tall.length - odd;
console.log('odd', odd);
console.log('even', even);
You were adding arr.length which is the array length. Instead you should simply increment the number
var tall = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50];
liste(tall);
function liste(arr) {
var sumOdd = 0;
var sumPar = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
sumPar++;
} else {
sumOdd++;
}
}
console.log("Odd : " + sumOdd);
console.log("Par : " + sumPar);
}
You always add the complete Length of the array to your variable
Try this instead of sumPar += arr.length;:
sumPar++;
I have this array:
var x = [1,2,3,4,5,"a","b","c",9,10];
I would like to slice this array into this pattern:
var x = [[1,2,3],[2,3,4],[3,4,5],[4,5,"a"],[5,"a","b"],["a","b","c"],["b","c",9],["c",9,10]];
I used the following code and been able to get [[1,2,3],[4,5,"a"],["b","c",9],[10,11,12]] . But it doesn't work for me. I need to get the pattern above.
var stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var x = ["a", "b", "c"];
var ad_time = 6;
var result = [];
var ad_index = stream.indexOf(ad_time);
if (~ad_index) {
for (var i = 0; i < x.length; i++) {
stream[ad_index + i] = x[i];
}
}
while (stream.length > 0) {
var chunk = stream.splice(0, 3);
result.push(chunk);
}
console.log(JSON.stringify(result));
Thanks in advence!
This code should do it:
var x = [1,2,3,4,5,"a","b","c",9,10];
var new_array = [];
for (var i = 0; i < x.length - 2; i++) {
new_array.push(x.slice(i, i + 3));
}
You can achieve it with a simple for loop:
var x = [1,2,3,4,5,"a","b","c",9,10];
var result = [];
for (var i = 0, il = x.length - 2; i < il; i++) {
result.push([x[i], x[i + 1], x[i + 2]]);
}
console.log(result);
EDIT: Array.slice() is more elegant, however it is much slower. On Chrome it is 80% - 85% slower according to this test. If you don't need to worry about performance, choose whichever you like. For example if you need to slice 8 elements from the array, then using x.slice(i + 8) is easier to write and read than [x[i], x[i + 1], x[i + 2], x[i + 3], ...]. However if performance matters, then direct access might be a better choice.