Iterating over Arrays in Javascript - javascript

I am a JavaScript newbie. I'm trying to practice some sample JavaScript problems. I'm a little stuck when it comes to this question about iterating over arrays. Can anyone point me in the right direction?
I am trying to take the values in oldArray, add 5 to each of them, and store in newArray.
var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42];
var newArray = [];
function plusFive(oldArray[i]) {
for (var i = 0; i < oldArray.length; i++) {
newArray.push(oldArray[i]) + 5) };
}
}

Bug in your code is an additional parenthesis and closing brace in push statement line, just remove them. Also there is no need to set function parameter here since both array are accessible inside the function, if you want to pass then you need to change it to function plusFive(oldArray), and call the function with array as parameter.
newArray.push(oldArray[i] + 5) ;
//-----------------------^----^-
Working snippet :
var newArray = [];
function plusFive(oldArray) {
for (var i = 0; i < oldArray.length; i++) {
newArray.push(oldArray[i] + 5)
};
}
plusFive([1,2,4,6,32,44]);
document.write(
'New array :' +
'<pre>' + JSON.stringify(newArray) + '</pre>'
);
Function without array as parameter
var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42];
var newArray = [];
function plusFive() {
for (var i = 0; i < oldArray.length; i++) {
newArray.push(oldArray[i] + 5)
};
}
plusFive();
document.write(
'Old array :' +
'<pre>' + JSON.stringify(oldArray) + '</pre>' +
'New array :' +
'<pre>' + JSON.stringify(newArray) + '</pre>'
);
But it's better to use map() for creating a modified array from an existing array
var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42];
var newArray = oldArray.map(function(v) {
return v + 5;
});
document.write(
'Old array :' +
'<pre>' + JSON.stringify(oldArray) + '</pre>' +
'New array :' +
'<pre>' + JSON.stringify(newArray) + '</pre>'
);

Your code is almost right, but you closed parenthesises incorrectly, and you need to name the function argument correctly. For function arguments, you're just giving labels. You can't name a variable something[a], and an argument cannot be named something[a].
Try:
var oldArray = [12, 45, 6, 23, 19, 20, 20, 15, 30, 42];
var newArray = [];
function plusFive(oldArray) {
for (var i = 0; i < oldArray.length; i++) {
newArray.push(oldArray[i] + 5)
}
}
plusFive();

Related

How many Odd and Even number are the in a array

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++;

How to push multiples of a number to array?

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]

Find all unique values that are sums of sub-arrays of an array of numbers... simple?

Sup fellow geeks!
I'm trying to make an array that lists all the possible values of the sums of the elements of an array. I'm sure this must be quite easy but I'm up to 2 or 3 hours now and I'm getting frustrated, I think I'm almost there...
var frootVals = [0,1,2,3,4,5]
var frootInc = frootVals
var fruitEnd = frootInc[frootInc.length-1]//begins at 5
var fruitAll = 15 // The total of all the numbers in the array. (this is actually
// calculated in another function, but lets just say I declared it as 15)
for (e = frootVals.length-2 ;fruitEnd !== fruitAll;e--){ //so I want it to
//finish when the final array entry is 15.
for (p = 1;p < e; p++){
var incEnd = frootInc[frootInc.length-p]
frootInc.push(incEnd + frootVals[p]) //1st time round (5 + 1 = 6, 5 + 2 = 7,
//5 + 3 =8, 5 + 4 = 9) THEN start again with 9 now being incEnd so pushes
//9+1 = 10 etc etc until the last digit is 15 and the whole loop stops...
}
}
EDIT - Basically the final result I'm after is frootInc to be be an array of the integers [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] - I'm sure I'll kick myself for giving up but I've only been learning a few weeks so this is all quite brain taxing.
After thinking about your question a bit, I think the easiest solution would be with recursion when the condition that the final value added to the array is less than the sum of values.
Here's a JS Fiddle for demo: http://jsfiddle.net/ukgzwpky/
To break it down a bit (and so that you may confirm I have the question right :D), say we have the following array:
[0, 1, 2, 3, 10, 15, 30]
The sum of the values are: 61. So the expected output array would be:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45, 46, 47, 48, 55, 60, 61]
To further break it down, the looping logic would do something like this:
// Get final value to add to previous values
var val = [0, 1, 2, 3, 10, 15, 30].pop();
// Add the final value - 30 - to all previous values (ignoring the zero)
.. loop here and push the values to our array ...
// For the first iteration, the updated array looks like:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45]
// New values calculated from: 30 + 1, 30 + 2, 30 + 3, 30 + 10, 30 + 15
At this point, our max value of 61 is less than the final value of 45 So, we do it again!
var val = [0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45].pop();
.. loop here and push the values to our array ...
// Second iteration, the updated array looks like:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45, 46, 47, 48, 55, 60, 61]
// New values are: 45 + 1, 45 + 2, 45 + 3, 45 + 10, 45 + 15
// Note that 45 + 30 would be greater than our sum of 61, so we break
If that's correct, here's a script that I wrote that populates such an array:
function getPopulatedArray(arr) {
var max = arguments[1] || getSum(arr),
current = arr.pop(),
temp = [],
i = 1,
len = arr.length;
// Populate temp array with values
for (; i < len; i++) {
if ((arr[i] + current) < max) {
temp.push(arr[i] + current);
} else {
temp.push(max);
break;
}
}
arr.push(current);
arr = arr.concat(temp);
// Done? Or should we continue?
if (arr[arr.length - 1] < max) {
return getPopulatedArray(arr, max);
} else {
return arr;
}
}
Again, the JS fiddle for demonstration: http://jsfiddle.net/ukgzwpky/
Hopefully this helps!
A very simple solution would be to do something like this:
var frootVals = [0,1,2,3,4,5]
var result = [];
for (var i = 0; i < frootVals.length; i++){ // Iterate over the array twice
for (var j = 0; j < frootVals.length; j++){ // To calculate all combinations
result.push(frootVals[i] + frootVals[j]);
}
}
Now, if you don't want duplicates, try this:
var frootVals = [0,1,2,3,4,5]
var result = [];
for (var i = 0; i < frootVals.length; i++){
for (var j = 0; j < frootVals.length; j++){
var value = frootVals[i] + frootVals[j];
if(result.indexOf(value) === -1){
result.push(value);
}
}
}
You could then use result = result.sort() if you want to output a sorted result.

Javascript : Loop through an array starting and ending at different indexs

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
}

Add leading zeros using javascript error

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;
}

Categories