loop over array, but not every element - javascript

I would like to iterate over the array and getting an average from 5 next elements, not from the whole array. I try to do it by code bellow, but it doesn´t work. I appreciate any kind of help or suggestions.
function standardDeviation(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
let tempArray = [];
const arrAvg = tempArray =>
tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
newArray += tempArray;
for (let j = array[i]; (j = array[i + 5]); i++) {
tempArray += array[j];
}
}
console.log(newArray);
return newArray;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
standardDeviation(arr);

You could slice a given array and take only five elements for getting an average.
function standardDeviation(array) {
const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));

You could try using the slice() function of array element.
// simulated loop index
var curr_index_pos = 3;
// entire array
var array_full = [1,2,3,4,5,6,7,8,9,10];
// array with 5 next values from "curr_index_pos"
var array_5 = array_full.slice(curr_index_pos,curr_index_pos+5);
var sum = 0;
for( var i = 0; i < array_5.length; i++ ) {
sum += parseInt( array_5[i] );
}
var avg = sum/array_5.length;
console.log("array_5", array_5);
// [4,5,6,7,8]
console.log("sum", sum);
// 30
console.log("avg", avg);
// 6

Related

array rotation results my array with empty value why is that

i am writing a simple program of array rotation.
when i console log element array , it includes empty along with other values.. why is that and whats the fix?
how can i remove empty ?
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let num = prompt("Enter Rotation Value : ");
const rotateFunc = (arr, d) => {
// debugger;
let result = [];
let temp = [];
let element = [];
for (let i = 0; i < arr.length; i++) {
if (i < d) {
temp[i] = +arr[i];
} else {
element[i] = +arr[i];
}
}
console.log(temp);
console.log(element);
result = element.concat(temp);
console.log(result);
};
rotateFunc(arr1, num);
results:
temp array console log result: (3) [1, 2, 3]
element array console log result: (9) [empty × 3, 4, 5, 6, 7, 8, 9]
and final result console log : (12) [empty × 3, 4, 5, 6, 7, 8, 9, 1, 2, 3]
When you assign to an element in the middle of an array, without assigning to the indexes before it, those earlier indexes still exist, they're marked "empty". Since you don't start assigning to element[i] until i is at least d, all the previous elements are empty.
Rather than assigning to specific indexes, use push() to append to the arrays starting from the beginning. Then you won't have gaps in the array.
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let num = prompt("Enter Rotation Value : ");
const rotateFunc = (arr, d) => {
// debugger;
let result = [];
let temp = [];
let element = [];
for (let i = 0; i < arr.length; i++) {
if (i < d) {
temp.push(arr[i]);
} else {
element.push(arr[i]);
}
}
console.log(temp);
console.log(element);
result = element.concat(temp);
console.log(result);
};
rotateFunc(arr1, num);
You also need to update your final array and remove the first d elements. You can use splice() to achieve it. It modifies the array in place
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let num = prompt("Enter Rotation Value : ");
const rotateFunc = (arr, d) => {
// debugger;
let result = [];
let temp = [];
let element = [];
for (let i = 0; i < arr.length; i++) {
if (i < d) {
temp[i] = +arr[i];
} else {
element[i] = +arr[i];
}
}
element.splice(0,d);
console.log(temp);
console.log(element);
result = element.concat(temp);
console.log(result);
document.write(result);
};
rotateFunc(arr1, num);

Why does my javascript's form loop return NAN while adding array

I am trying to add all array elements with basic for loop for some reason, my variable 'result' return NaN.
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i <= arr.length; i++) {
result = arr[i] + result
}
console.log(result)
}
arraySum(array)
Please use basic looping to answer, I tried .reduce method but want to use basic loops
Thank you
Your condition of i <= arr.length should be using i < arr.length
The length of the array is 5 but the index of the last number is 4, so you don't want <= there.
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i < arr.length; i++) {
result = arr[i] + result
}
console.log(result)
}
arraySum(array)
Length start at 1, so you need to set < operator in your loop :
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i < arr.length; i++) {
result = arr[i] + result
console.log(result)
}
console.log("result = ", result)
}
arraySum(array)
The reason for this problem is that the array has a length of 5 and the last index is 4. When the loop is at index = 5 there is no element at position 5. The result will therefore be undefined. To avoid this problem, the for loop should be like this:
for (let i = 0; i < arr.length; i++)
or
for(const i in arr)
You put '<=' in the for loop but you must use just '<'.
if array = [1,2,3] then length = 3 but array index goes from 0 to 2 not 3
you could try, if simple enough:
let array = [1, 2, 3, 4, 5];
let result = 0;
arraySum = (arr) => {
for (let i = 0; i < arr.length; i++) {
result += arr[i]
}
console.log(result)
}
arraySum(array)
the "<=" shoud be placed by "<"
let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
for (let i = 0; i <= array.length; i++) {
result += array[i];
}
console.log(result);
};
arraySum(array);

Sort Array to 1st min, 1st max, 2nd min, 2nd max, etc

Write a JS program to return an array in such a way that the first element is the first minimum and the second element is the first maximum and so on.
This program contains a function which takes one argument: an array. This function returns the array according to the requirement.
Sample Input: array=[2,4,7,1,3,8,9]. Expected Output: [1,9,2,8,3,7,4].
const arrsort=(arr)=>{
return arr.sort(function(a, b){return a - b});
}
const test=(arr)=>{
arr=arrsort(arr);
var arr2=[];
var j=0;
var k=arr.length-1;
for (var i=0;i<arr.length-1;i++){
if(i%2===0){
arr2.push(arr[j]);
j++;
}
else{
arr2.push(arr[k]);
k--;
}
}
return arr2;
}
Instead of using two indices, you could shift and pop the values of a copy of the sorted array.
var array = [2, 4, 7, 1, 3, 8, 9]
const arrsort = arr => arr.sort((a, b) => a - b);
const test = (arr) => {
var copy = arrsort(arr.slice()),
result = [],
fn = 'pop';
while (copy.length) {
fn = { pop: 'shift', shift: 'pop' }[fn];
result.push(copy[fn]());
}
return result;
}
console.log(test(array));
You can first sort() the array in ascending order and then loop through half of the array. And push() the values at corresponding indexes.
let arr = [2,4,7,1,3,8,9];
function order(arr){
let res = [];
arr = arr.slice().sort((a,b) => a-b);
for(let i = 0; i < Math.floor(arr.length/2); i++){
res.push(arr[i],arr[arr.length - 1 - i]);
}
return arr.length % 2 ? res.concat(arr[Math.floor((arr.length - 1)/2)]) : res;
}
console.log(order(arr))
You could sort the array, then copy and reverse and push to another array
const a = [2,4,7,1,3,8,9];
a.sort();
const b = a.slice().reverse();
const res = [];
for (let i = 0; i < a.length; i++) {
if (res.length < a.length) res.push(a[i]);
if (res.length < a.length) res.push(b[i]);
}
console.log(res);
Or use a Set
const a = [2,4,7,1,3,8,9];
a.sort();
const b = a.slice().reverse();
const res = new Set();
a.forEach((e, i) => (res.add(e), res.add(b[i])));
console.log(Array.from(res));
There are many ways are available to do this. And my solution is one of themm i hope.
Find max and min value, push them into another array. And delete max, min from actual array.
let array=[2,4,7,1,3,8,9];
let finalArray = [];
let max, min;
for(let i = 0; i < array.length; i++) {
max = Math.max(...array);
min = Math.min(...array);
finalArray.push(min);
finalArray.push(max);
array = array.filter(function(el) {
return el != max && el != min;
})
}
console.log(finalArray);
After sorting array this would work
myarr = [1,2,3,4,5,6];
let lastindex = myarr.length-1;
for(let i = 1 ; i <= myarr.length/ 2; i = i+2) {
ele = myarr[i];
myarr[i] = myarr[lastindex];
myarr[lastindex] = ele;
lastindex--;
}
Final Output will be: [1, 6, 3, 5, 4, 2]
You can use two iterators after sorting your array, one goes ascending and the other goes descending, until they cross each other.
Here's the code:
const array = [2, 4, 7, 1, 3, 8, 9];
const test = arr => {
const result = [];
const sortedArr = array.sort((a, b) => a - b);
for (let i = 0, j = sortedArr.length - 1; i <= j; i++, j--) {
result.push(sortedArr[i]);
i == j || result.push(sortedArr[j]);
}
return result;
};
console.log(test(array));
You can easily achieve the result using two pointer algorithm
function getValue(arr) {
const result = [];
let start = 0,
end = arr.length - 1;
while (start < end) result.push(arr[start++], arr[end--]);
if (start === end) result.push(arr[start]);
return result;
}
const array = [2, 4, 7, 1, 3, 8, 9];
const sorted = array.sort();
console.log(getValue(sorted));

How to calculate the sum of each element of an array and its previous elements in JavaScript?

For example, if I have an array [1,2,3,4], I want to calculate 1+2, 1+2+3 and 1+2+3+4 and return a new array. How can I do that?
let arr = [1, 2, 3, 4];
doSomething(arr);
output...
newArr = [1, 3, 6, 10];
Add this function.
function dosomething (arr) {
var i;
if(i === 1 || i === 0) return arr;
for(i = 1; i<arr.length; i++){
arr[i] += arr[i-1];
}
return arr;
}
You could slice the array for getting the wanted elements and reduce the value for getting a sum.
Methods:
Array#map for getting a new array of the sum,
Array#slice returns a part of the array,
Array#reduce for adding all values.
var array = [1, 2, 3, 4],
sums = array.map((_, i, a) => a.slice(0, i + 1).reduce((a, b) => a + b));
console.log(sums);
Fun with a closure over the sum
var array = [1, 2, 3, 4],
sums = array.map((a => b => a += b)(0));
console.log(sums);
Some elegant method:
function getArrSum(arr)
{
if(!arr.length) return [];
let tmp=[arr[0]];
for(let i=1; i<arr.length; i++)
{
tmp.push(tmp[i-1]+arr[i]);
}
return tmp;
}
let arr=[1,2,3,4];
console.log(getArrSum(arr));
You can try to use array.reduce
let arr = [1, 2, 3, 4];
let newArr = [];
arr.reduce((prev, current) => {newArr.push(prev+current); return prev + current}, 0);
console.log(newArr);
Fist of all I would like to share a link which shows what should be a good question.
https://stackoverflow.com/help/how-to-ask
and about the calculation of the array is :
function getArray(numbers)
{
if(!numbers.length) return [];
let array=[numbers[0]];
for(let i=1; i < numbers.length; i++)
{
array.push(array[i-1]+numbers[i]);
}
return array;
}
let array=[1,2,3,4];
let procArray = [];
console.log(getArray(array));
var a = [1,2,3,4];
var b=[];
for(i=0;i<a.length;i++)
{
var sum = 0;
for(j=0;j<=i+1;j++)
{
if(a[j] != null)
sum=sum+a[j];
}
b[i]=sum;
}

Sort an array containing numbers using a 'for' loop

I am new to JavaScript, and I have an array which contains numbers.
var arr = [2,4,8,1,5,9,3,7,6];
How can I sort it using a native for loop in JavaScript?
I know sort function is available, but I want it through for loop.
The output should be:
var res = [1,2,3,4,5,6,7,8,9];
var Arr = [1, 7, 2, 8, 3, 4, 5, 0, 9];
for (var i = 1; i < Arr.length; i++)
for (var j = 0; j < i; j++)
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
console.log(Arr);
I would do something like this...
var input = [2,3,8,1,4,5,9,7,6];
var output = [];
var inserted;
for (var i = 0, ii = input.length ; i < ii ; i++){
inserted = false;
for (var j = 0, jj = output.length ; j < jj ; j++){
if (input[i] < output[j]){
inserted = true;
output.splice(j, 0, input[i]);
break;
}
}
if (!inserted)
output.push(input[i])
}
console.log(output);
Maybe there are more efficient ways, but if you want to use the for loop, it's my first idea...
First create an empty array where the sorted numbers will be pushed into.
let sorted = [];
Secondly, create a very large amount of numbers that none of the numbers of the array can match. This number will be used for the very first comparison to determine which number of the array is smaller.
let comparison = 9000000000;
Create a for loop.
This loop will have another loop inside of it. The inner loop will check for the smallest number in a given array, and once the smallest number is gotten, it will be push into the empty array we created. The smallest number will also be removed from the initial array and then the array will run again.
for(a = 0; a < arr.length; a++){
//This inner loop fetches the smallest number.
for(b = 0; b < arr.length; a++){
if(comparison > arr[b]){
comparison = arr[b];
}
}
// The smallest number is assigned to comparison
// Now it being pushed to the empty array
sorted.push(comparison);
// Remove the smallest number from the initial array
let indexOfSmallNumber = arr.indexOf(comparison);
arr.splice(indexOfSmallNumber, 1);
// Set the comparison back to 9000000000;
comparison = 90000000000;
a = -1;
// Here, "a" is our main loop index counter and we are
// setting it to -1 because we don't want it to change
// to 2 by default, doing this will make the loop run
// forever until the initial array is empty.
}
let arr = [4, 2, 5, 1]
let temp;
function converter(arr) {
for(let i=0; i<arr.length; i++) {
for (let j=i+1; j<arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
return arr
}
const newArr = converter(arr)
console.log(newArr)
Use:
let s = [4, 6, 3, 1, 2];
for (let i = 0; i < s.length;) {
if (s[i] > s[i + 1]) {
let a = s[i];
s[i] = s[i + 1];
s[i + 1] = a;
i--;
}
else {
i++;
}
}
This is a sorting algorithm which has a best time complexity of O(n) and the worst time of O(n^2).
This code checks for each number, and then compares to all numbers on the left side.
To check the time it takes each code to run, you can also use this code below:
let start = process.hrtime.bigint()
let end = process.hrtime.bigint()
console.log(end - start) // This measures the time used in nano seconds.
Also for microseconds, you can use this performance.now().
Here there is a very simple solution that uses a temporary array to store the values greater than the current one. Then it puts the current value between the lesser and the greater values:
var arr = [2,4,8,1,5,9,3,7,6];
var res = [];
for (const c of arr) {
let tmp = [];
while (c < res[res.length-1]) {
tmp.unshift(res.pop());
}
res = [...res, c, ...tmp];
}
const numberArr = [5, 9, 2, 8, 4, 10, 1, 3, 7, 6];
function sortedFunction(arr) {
let sortedArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
let n = 0;
if (arr[i] > arr[j]) {
n = arr[i];
arr[i] = arr[j];
arr[j] = n;
}
}
sortedArr.push(arr[i]);
}
return sortedArr;
}
sortedFunction(numberArr);
Under the JavaScript array sort section of W3Schools it talks about how to compare a value in an array with the others and then order them based on the values being returned. I updated the code to use a for loop to sort values.
// Ascending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
points.sort(function (a, b) {
return a - b
});
output += points[i] + "<br>";
}
console.log(output);
// Descending points
var points = [5.0, 3.7, 1.0, 2.9, 3.4, 4.5];
var output = [];
var i;
for (i = 0; i < points.length; i++) {
points.sort(function (a, b) {
return b - a
});
output += points[i] + "<br>";
}
console.log(output);
const array = [12, 3, 45, 61, 23, 45, 6, 7];
function sortArray(array) {
for (var i = 0; i < array.length; ++i) {
for (var j = 0; j < array.length - 1 - i; ++j) {
if (array[j] > array[j + 1]) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
}
}
}
return array;
}
console.log(sortArray(array));
Here are the two solutions for the same algorithm:
Solution 1:
We can directly use JavaScript functions:
let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6]
const changeOrder = (arr) => {
return arr.sort((a, b) => a - b)
}
let result = changeOrder(arr);
console.log(result) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Solution 2:
We can use a JavaScript for loop for doing the same
let arr = [2, 4, 8, 1, 5, 9, 3, 7, 6]
const changeOrder = (arr) => {
for(let i=1; i< arr.length; i++) {
for(let j=0; j < i; j++) {
if(arr[i] < arr[j]) {
let x = arr[i]
arr[i] = arr[j]
arr[j] = x
}
}
}
return arr;
}
let result = changeOrder(arr);
console.log(result) // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
An improvement to previous answer
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

Categories