How to add items into an Array if they sum - javascript

I have this array:
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
I'd like to know if is there somehow to create a new array only if the sum of them are less than a global array using a loop or something, example
var dia = 122;
var dia_new = [31, 28, 31, 30]; //This because they sum less than the given var (dia).
Thanks for your answer

Use a Javascript for-loop and check the count in every iteration.
If the count is lesser than dia then push that number into the array.
for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++)
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var dia = 122;
var count = 0;
var array = [];
for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++) {
count += mes_dias[i];
array.push(mes_dias[i]);
}
console.log(array);
.as-console-wrapper {
max-height: 100% !important
}
if dia is an array of numbers, and its sum is the max days for the new array:
The reduce function will sum the elements in array_dia.
var dia = array_dias.reduce((a, n) => a += n, 0);
var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var array_dias = [30, 30, 31, 31];
var dia = array_dias.reduce((a, n) => a += n, 0);
console.log(dia)
var count = 0;
var array = [];
for(var i = 0; i < mes_dias.length && (count + mes_dias[i] < dia); i++) {
count += mes_dias[i];
array.push(mes_dias[i]);
}
console.log(array);
.as-console-wrapper {
max-height: 100% !important
}

You can reduce your array into a new array:
let mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let dia = 120;
let dia_new = mes_dias.reduce( (dia_acc, dias) => {
dia -= dias;
if (dia >= 0)
dia_acc.push(dias);
return dia_acc;
}, []);
EDIT 1: Based on Angel Politis' answer, another elegant solution can be:
let dia_new = mes_dias.slice(0, mes_dias.findIndex( (dias) => (dia -= dias) < 0));
EDIT 2: Based on Ele's answer, this way offers same, if not better, performance and is more readable in my view. Remember, in worst case scenario we loop 12 times.
let array = [],
sum = 0;
// Add days until they sum to more than 'dia'
for(let i = 0; i < mes_dias.length; ++i) {
sum += mes_dias[i];
if (sum > dia)
break;
array.push(mes_dias[i]);
}

var mes_dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var dia = 122;
var total = 0;
var newarray = new Array();
for(var i = 0; i < mes_dias.length && (total + mes_dias[i]) <= dia; i++) {
newarray.push(mes_dias[i]);
total = total + mes_dias[i];
console.log(newarray);
}

One way to achieve what you want would be using a loop in which you:
progressively sum the elements of mes_dias.
cache the index of the last element, if sum <= dia.
Then, you can use slice to get the portion of the array until the last index.
Snippet:
var
arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], // mes_dias
max = 122, // dia
last,
newArr;
/* Iterate over every element of the array until sum > max and save the index. */
for (let i = 0, sum = 0, l = arr.length; i < l && sum <= max; sum += arr[++i]) {
last = i;
}
/* Get the portion of the array until the index. */
newArr = arr.slice(0, last);
/* Log the result. */
console.log(newArr);

Related

How do I iterate though an array and do actions based on conditions?

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

switchMaxMin-Java Script

I have to write a function switchMaxMin(tab, n) that swaps the maximum element with the minimum element in an n-element array tab. We assume that all elements of the array are distinct (i. e. there are not a few maxima or minima). I don't know how to do this
I started to write the code and I came up with this:
var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = tab[0];
var max = tab[0];
document.write("Tablica: ");
for (i = 1; i < tab.length; i++) {
document.write(tab[i] + ", ");
if (min > tab[i]) {
min = tab[i];
}
if (max < tab[i]) {
max = tab[i];
}
}
document.write("<br /><br />Max: " + max);
document.write("<br />Min: " + min);
To swap the elements you have also to store the indices of the max and min elements
if (min > tab[i]) {
min = tab[i];
minIndex = i;
}
if (max < tab[i]) {
max = tab[i];
maxIndex = i;
}
Then you can reassign it by a classical swap function
function swapper(maxInd, minInd) {
let temp = tab[maxInd];
tab[maxInd] = tab[minInd]
tab[minInd] = temp;
}
var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = tab[0];
var max = tab[0];
var minIndex = 0;
var maxIndex = 0;
document.write("Tablica: ");
for (let i = 1; i < tab.length; i++) {
document.write(tab[i] + ", ");
if (min > tab[i]) {
min = tab[i];
minIndex = i;
}
if (max < tab[i]) {
max = tab[i];
maxIndex = i;
}
}
swapper(maxIndex, minIndex);
document.write("<br /><br />Max: " + max);
document.write("<br />Min: " + min);
document.write("<br /> After the swap " + tab.join(","));
function swapper(maxInd, minInd) {
let temp = tab[maxInd];
tab[maxInd] = tab[minInd]
tab[minInd] = temp;
}
Just another way to do it, slightly less efficient, but fewer lines of code.
var tab = new Array(6, 4, 65, 34, 67, 89, 45, 7, 35, 79, 23, 56, 87, 12, 38, 9);
var min = Math.min.apply(null,tab);
var minIndex = tab.indexOf(min);
var max = Math.max.apply(null,tab);
var maxIndex = tab.indexOf(max);
var temp = tab[minIndex]
tab[minIndex] = tab[maxIndex]
tab[maxIndex] = temp;
console.log(tab)

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]

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