Adding an element to an array from inside a for loop - javascript

in the for loop below I have arr[i] = x * i; I am basically trying to get multiples of numbers. the results of the code I have now is [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] I do not want the first element of the array to be 0 ..
var n = 10;
var arr = [];
var x = 2;
for(var i = 0; i < n; i++ ){
//arr[0] = x;
arr[i] = x * i;
// arr.push(x += x)
}
console.log(arr)
i want to be able to do arr[0] and see x. In this case that would be 2 (the number for the multiples..I don't know math words) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
I know that the problem is that 2 * 0 is equal to 0 so arr[0] = 0. what is the best way to make it so that the first element will be the second loop. I was thinking about making an if statement. or using an array method that slices of the beginning of the array. I hope there is an easier way like changing the for loop.

There are two simple ways to fix this
Change the loop starting value
var arr = [],
x = 2,
n = 10;
for (var i = 1; i <= n; i++) { // Start with `1`
arr.push(x * i);
}
Or, multiply with the next value of i,
var arr = [],
x = 2,
n = 10;
for (var i = 0; i < n; i++) {
arr.push(x * (i + 1)); // Multiply with i + 1
}
If you still want to solve it with array index assignment, then just remove the first element, with Array.prototype.slice after creating the entire array, like this
var n = 10,
arr = [],
x = 2;
for (var i = 0; i <= n; i++) { // Note the limits, 0 to <= n
arr[i] = x * i;
}
console.log(arr);
// [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]
arr = arr.slice(1);
console.log(arr);
// [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]

Related

Resetting index in a for loop

This function needs to find the first occurrence of consecutive numbers whose sum equals 10, and return them as an array. My idea was to keep summing the numbers until the accumulator, in this case x becomes greater than 10, at which point the value of x is reset to zero, and i is reset back to index 1, by being assigned to the ct variable that is supposed to grow by one on each reset, so the loop would go back and start at the next element, until it gets the correct value. But for some reason ct is stuck at 1 and doesn't grow and the loop doesn't move past the second array element at index 1. Is there an error in the logic or the implementation?
Warning: This code may cause the page to crash or become unresponsive
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
for (let i = 0; i < arr.length; i++) {
let ct = 0;
x = x + arr[i]
if (x > 10) {
x = 0;
i = ct;
ct++
}
console.log(x)
}
}
console.log(test(arr))
The problem is that you've defined ct in the wrong place. It's inside the loop, meaning that every time you get to a point where i = ct, i is reset to 0 and ct++ has no effect (because every iteration, ct is reset to 0). You need to define ct in the same scope as x:
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
let ct = 0;
for (let i = 0; i < arr.length; i++) {
x = x + arr[i];
if (x > 10) {
x = 0;
i = ct;
ct++;
}
console.log(x);
}
}
test(arr);
I've also filled in the rest of the logic of the function for you in case you'd like it:
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
let ct = 0;
let result = [];
for (let i = 0; i < arr.length; i++) {
x = x + arr[i];
if (x > 10) {
x = 0;
i = ct;
ct++;
}
if (x == 10) {
result = arr.slice(ct, i + 1);
return result;
}
console.log(x);
}
return result;
}
console.log(test(arr));

Javascript Challenge: Loops - Multiple Conditions - stuck and can't figure this out

I did this module on functions and execution context - all questions have gone well but there is one challenge I have spent a lot of time on and still can't figure it out. Any help will be greatly appreciated. Thank you
Challenge question says:
Write a function addingAllTheWeirdStuff which adds the sum of all the odd numbers in array2 to each element under 10 in array1.
Similarly, addingAllTheWeirdStuff should also add the sum of all the even numbers in array2 to those elements over 10 in array1.
BONUS: If any element in array2 is greater than 20, add 1 to every element in array1.
// Uncomment these to check your work!
// console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15], [1, 2, 3, 4, 5])); // expected log [10, 12, 14, 23, 21]
// console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15, 1], [1, 2, 3, 4, 5, 22])); // expected log [11, 13, 15, 46, 44, 11]
// my attempt so far:
function addingAllTheWeirdStuff(array1, array2) {
// ADD CODE HERE
let result = []
for (let i = 0; i < array2.length; i++) {
if (array2[i] > 20) {
result = array1[i] += 1
}
}
for (let i = 0; i < array2.length; i++) {
if (array2[i] % 2 === 0 && array1[i] > 10) {
result = array1[i] + array2[i]
}
}
for (let i = 0; i < array2.length; i++) {
if (array2[i] % 2 !== 0 && array1[i] < 10) {
result = array1[i] + array2[i]
}
}
return result
}
You can easily achieve this using reduce and map array method, with the ternary operator:
const array1 = [1, 3, 5, 17, 15];
const array2 = [1, 2, 3, 4, 5];
function addingAllTheWeirdStuff(array1, array2) {
const oddSum = array2.reduce((sum, current) => current % 2 ? current + sum : 0 + sum, 0)
const oddEven = array2.reduce((sum, current) => current % 2 == 0 ? current + sum : 0 + sum, 0)
return array1.map(num => num < 10 ? num + oddSum : num + oddEven)
}
console.log(addingAllTheWeirdStuff(array1, array2))
If you break the challenge into smaller pieces, you can deconstruct it better and come up with your solutions.
This is what I did... I will be adding more comments shortly with more explanations
I chose to keep using loops as I assumed this was the point of the challenges (to practice for loops, multiple conditions, etc) - In other words, I chose to not use map / reduce on purpose but if that's allowed, use the answer by #charmful0x as it results in less code :)
// function to get sum of all odd numbers in array
function getSumOfAllOddNumbersInArray( elementArray ){
var sumOfOddNumbers = 0;
for (let i = 0; i < elementArray.length; i++) {
// use remainder operator to find out if element is odd or not
if (elementArray[i] % 2 !== 0 ) {
sumOfOddNumbers += elementArray[i];
}
}
return sumOfOddNumbers;
}
// function to get sum of all EVEN numbers in array
function getSumOfAllEvenNumbersInArray( elementArray ){
var sumOfEvenNumbers = 0;
for (let i = 0; i < elementArray.length; i++) {
// use remainder operator to find out if element is odd or not
if (elementArray[i] % 2 === 0 ) {
sumOfEvenNumbers += elementArray[i];
}
}
return sumOfEvenNumbers;
}
// Return true if there is at least one element in array that is greater than 20
function hasElementOverTwenty( elementArray ){
for (let i = 0; i < elementArray.length; i++) {
if (elementArray[i] > 20 ) {
// no need to keep looping, we found one - exit function
return true;
}
}
return false;
}
function addingAllTheWeirdStuff( firstArray, secondArray ){
var sumOfOddNumbersInArray = getSumOfAllOddNumbersInArray( secondArray );
var sumOfEvenNumbersInArray = getSumOfAllEvenNumbersInArray( secondArray );
var needToAddOne = hasElementOverTwenty( secondArray );
for (let i = 0; i < firstArray.length; i++) {
// Challenge One
if (firstArray[i] < 10) {
firstArray[i] = firstArray[i] + sumOfOddNumbersInArray;
} else if (firstArray[i] > 10) {
// Challenge Two
firstArray[i] = firstArray[i] + sumOfEvenNumbersInArray;
}
// bonus
if( needToAddOne ){
firstArray[i]++;
}
}
return firstArray;
}
// Uncomment these to check your work!
console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15], [1, 2, 3, 4, 5]));
console.log('expected:' + [10, 12, 14, 23, 21] );
console.log(addingAllTheWeirdStuff([1, 3, 5, 17, 15, 1], [1, 2, 3, 4, 5, 22]));
console.log('expected:' + [11, 13, 15, 46, 44, 11] );
Challenge question says: Write a function addingAllTheWeirdStuff which adds the sum of all the odd numbers in array2 to each element under 10 in array1.
Similarly, addingAllTheWeirdStuff should also add the sum of all the even numbers in array2 to those elements over 10 in array1.
BONUS: If any element in array2 is greater than 20, add 1 to every element in array1.

How to transpose 2D square matrix stored as 1D array in Javascript

My question is closely related to this question but I'm looking for a solution in Javascript
How to Transpose 2D Matrix Stored as C 1D Array
Basically I have a 2D square matrix
1 2 3
4 5 6
7 8 9
Stored as follows
let anArray = [1 ,2, 3, 4, 5, 6, 7, 8, 9]
How can I transpose this matrix so that the elements of my source array are switched as follows?
let newArray = [1, 4, 7, 2, 5, 8, 3, 6, 9]
You could take the length for the dimension of the array and map items on a specific index for a new array.
var array = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
n = Math.sqrt(array.length),
transposed = array.map((_, i, a) => a[(i % n) * n + Math.floor(i / n)]);
console.log(transposed.join(' '));
The approach in the answer you linked to works well in JavaScript too.
For a 3 x 3:
const anArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArray = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
newArray[3 * i + j] = anArray[3 * j + i];
}
}
console.log(newArray);
For an N x N, just replace the 3's with N.
This answer avoids division and flooring (integer division) and a decent optimizer should make the code relatively fast. You might also consider initializing the new array with
let newArray = new Array(9);
or
let newArray = new Array(N * N);
but profile the code before attempting "optimizations" such as this.
var arr1 = [];
var arr2 = [];
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
arr1.push(mat[i][j]);
}
}
for(int j=0; j<mat[i].length; j++) {
for(int i=0; i<mat.length; i++) {
arr2.push(mat[i][j]);
}
}
Set a max "width" for your matrix and insert into a new array in loops, offset by 1 for each run.
function transpose(list, width) {
if (width === void 0) {
width = 1;
}
var t = 0;
var transposed = [];
while (t < width) {
for (var index = t; index < list.length; index += width) {
transposed.push(list[index]);
}
t++;
}
return transposed;
}
//TEST
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var transposed = transpose(list, 3);
console.log(list.join());
console.log(transposed.join());

Sum Function with array argument

i'm starting studying javascript. I'm stuck with this exercise: Create a function that takes an array as argument and return the sum of all elements of the array.
I have written this code:
function sum(table) {
let x = table[0];
let y = [table.length - 1];
let totale = 0;
for (count = x; count <= y; count++) {
total += x;
x += 1;
};
return total;
};
console.log(sum[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
I don't know why the result is undefined instead of 55. Thanks for helping.
total not totale
the function call needs parentheses as sum([…])
y = table.length - 1 you want the length, not an array that holds the length
x = 0 you don't need to set it to the first element of the array
total += table[count]; you don't need to set it to x or to deal with x at all
function sum(table) {
let x = 0;
let y = table.length - 1;
let total = 0;
for (count = x; count <= y; count++) {
total += table[count];
};
return total;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Quicker Solution
function sum(table) {
return table.reduce((p,c)=>p+c,0);
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Here are couple of things.
You need to execute the sum function by calling like sum([array elements]) .Note the ( & ) braces
Secondly count <= y will give undefined as it will exceed the length of the array. The array index starts from 0;
There is a typo here totale.
You can avoid these set of lines
let x = table[0];
let y = [table.length - 1];
if you just initialize the loop conditional statement like this
for (let count = 0; count < table.length; count++)
function sum(table) {
let x = 0
for (let count = 0; count < table.length; count++) {
x += table[count];
};
return x;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Another option is to use the reduce method
function sum(table) {
return table.reduce(function(acc, curr) {
return acc += curr;
}, 0) // 0 is the initial value
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

How to add item in array every x items?

How can I add an item every x item in an array?
For example I would like to add an item every 10 items in the 3rd position:
const arr = [1,2];
const result = [1,2, item];
or
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
const result = [1,2,item,3,4,5,6,7,8,9,10,11,item,12,13,14,15,16];
You could take a while loop and check the length after taking the starting position and the interval length as increment value.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
pos = 2;
interval = 10;
while (pos < array.length) {
array.splice(pos, 0, 'item');
pos += interval;
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here's an option that doesn't alter the original array.. just loop and insert to a new array.
/**
* Add an item to an array at a certain frequency starting at a given index
* #param array arr - the starting array
* #param mixed item - the item to be inserted into the array
* #param integer starting = the index at which to begin inserting
* #param integer frequency - The frequency at which to add the item
*/
function addItemEvery(arr, item, starting, frequency) {
for (var i = 0, a = []; i < arr.length; i++) {
a.push(arr[i]);
if ((i + 1 + starting) % frequency === 0) {
a.push(item);
i++;
if(arr[i]) a.push(arr[i]);
}
}
return a;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
arr = addItemEvery(arr, "item", 2, 3);
console.log(arr);
Use arr.splice method. Calculate index for every tenth element like 2,12,22...
var arr = [];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());
For more reference
How to insert an item into an array at a specific index?

Categories

Resources