loop push to a new array the numbers in an array - javascript

i have the below code that is not working.
var array = [1, 3, 2]
var newArray = []
getNewArray() {
for (let i = 0; i < array.length; i++) {
for (let x = 0; x < array[i]; x++) {
this.newArray.push(array[i]);
}
}
console.log(this.newArray);
}
What i would like to achieve is to use the numbers in a array to loop through the number of times. with the results as shown below
(3) [{…}, {…}, {…}]
0:
count:(1) [1]
1:
count:(3) [1,2,3]
2:
count:(2) [1,2]
Right now it is displaying as
(4) [1, 2, 2, 1]
0: 1
1: 2
2: 2
3: 1

Since you are using ES6 features, you can try a combination of .map + Array.from.
Idea:
Use Array.map and loop over every item.
Use this item as length and create a new array using Array.from.
Pass a mapper function to populate array.
var array = [1, 3, 2];
var result = array.map((item) => Array.from({
length: item
}, (_, i) => i + 1));
console.log(result)

Try this
var array = [1, 3, 2]
var newArray = []
function getNewArray() {
for (let i = 0; i < array.length; i++) {
var tmp = [];
for (let x = 0; x < array[i]; x++) {
tmp.push(x+1);
}
this.newArray.push(tmp);
}
}
getNewArray();
console.log(this.newArray);

var array = [1, 3, 2];
var newArray = [];
function getNewArray() {
for (let i = 0; i < array.length; i++) {
var tempArray = [];
for (let x = 0; x < array[i]; x++) {
tempArray.push(array[i]);
}
newArray.push(tempArray);
}
console.log(this.newArray);
}
getNewArray();

With some array magic
var array = [1, 3, 2]
var newArray = []
let getNewArray = () => {
newArray = array.map( x => Array(x).fill().map( (_,i) => i+1 ) )
console.log(newArray);
}
getNewArray()

Related

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

loop over array, but not every element

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

Javascript: Turn a nested array into a single array using a nested for loop

This is just a simple javascript exercise that I'm working on.
I'm trying to convert this array...
var array = [
[1,2],
[3,4],
[5,6]
];
into...
array = [1, 2, 3, 4, 5, 6];
by using this nested for loop.
var series;
var storage = [];
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
series = array[i][j];
for (var k = 0; k < 6; k++) {
storage[k] = series;
};
};
};
console.log(storage);
With an output of...
//Output: [6, 6, 6, 6, 6, 6]
Why is this the output and how can I fix it?
for (var k = 0; k < 6; k++) { is not required . array[i] will be each of element inside main array , so iterating over array[i] you can access each of the element
var array = [
[1, 2],
[3, 4],
[5, 6]
];
var series;
var storage = [];
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
storage.push(array[i][j])
};
};
console.log(storage);
series = array[i][j];
for (var k = 0; k < 6; k++) {
storage[k] = series;
};
Seriously, here you set the same value to each element of the resulting array.
You probably need something like
for(let x of array) {
for(let y of x) {
storage.push(y)
}
}
Or, if your JS machine is experimental enough, simply
var storage = array.flat()
You can use a mix of reduce and concat to achieve what you want in one line
var array = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(array.reduce((a, v) => a.concat(v), []));
As for why your code didn't work, it's mainly down to this bit
for (var k = 0; k < 6; k++) {
storage[k] = series;
};
It would overwrite everything in the array with the last value of series, which in your case would be 6
Array.concat can do this on its own
var merged = [].concat.apply([], array);
var array = [
[1,2],
[3,4],
[5,6]
];
var newArray = [];
for (let i = 0; i < array.length; i++) {
newArray = newArray.concat(array[i]);
}
console.log(newArray)
You can use array.flat()
Reference : flatten
var array = [
[1,2],
[3,4],
[5,6]
];
array.flat();
// 1,2,3,4,5,6....
You could use the ES6 spread syntax like this:
for (let element of array){
storage.push( ... el )
}
storage = [];
for(var i=0; i<array.length; i++)
storage = storage.concat(array[i]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Categories