I want to generate the following array:
[3, 3, 3, 3, 4, 4, 5, 5, 5]
there are 3 different values that should repeat m, n, and k times. What is the easiest way to do that?
If I do Array(m + n + k).fill(...).fill(...).fill(...) the start and end points in later fill calls look not very straightforward.
Generate the arrays separately and then combine them into one final array
[
...Array(4).fill(3),
...Array(2).fill(4),
...Array(3).fill(5)
]
Create an array of values, and an array of repeat. Iterate the values with Array.map(), and return a new array filled with the values. Flatten by spreading into Array.concat():
const values = [3, 4, 5];
const repeat = [4, 2, 3];
const arr = [].concat(...values.map((v, i) => new Array(repeat[i]).fill(v)));
console.log(arr);
var arrValues = [3,4,5];
var arrRepeats = [4,2,3];
var arr = [];
for(var i =0; i< arrRepeats.length;i++){
arr.push(Array(arrRepeats[i]).fill(arrValues[i]));
}
console.log(arr)
Or
var arrValues = [3,5,4];
var arrRepeats = [4,2,3];
let arr = [];
for(var i =0; i< arrRepeats.length; i++){
for(var j=0; j<arrRepeats[i];j++){
arr.push(arrValues[i]);
}
}
console.log(arr)
Or you can do that if you wanna generate arrays and combine them
var arrValues = [3,5,4];
var arrRepeats = [4,2,3]; // m, n, k
var mainArr = [];
for(var i =0; i< arrRepeats.length; i++){
var arr = [];
for(var j =0; j < arrRepeats[i]; j++){
arr.push(j);
arr.fill(arrValues[i]);
}
mainArr.push(arr);
}
console.log(mainArr)
Related
I did try this
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 3, 4, 5, 6];
var sum = [];
for (var i = 0; arr1[i] < arr1.length; i++) {
for (var j = 0; arr2[j] < arr2.length; j++) {
sum = sum.push(arr1[i] + arr2[j]);
}
}
console.log(sum);
Found the right solution, However trying to understand where my code is going wrong. It says sum is not defined.
Do let me know or any ref would also do good.
Thanks Folks
Array.push does not return a new array. It modifies the given array. So basically you just need to change:
sum = sum.push(arr1[i] + arr2[j]);
To:
sum.push(arr1[i] + arr2[j]); //without the assignment
And it should work!
Assuning you want a new array with sum of each value at same index, you could take a single loop and add the values at same index.
Array#push returns the new length of the array, and has nothing to do with the pushed value.
var arr1 = [1, 2, 3, 4, 5],
arr2 = [2, 3, 4, 5, 6],
sum = [];
for (var i = 0; i < arr1.length; i++) {
sum.push(arr1[i] + arr2[i]);
}
console.log(sum);
Array.push is mutating the original array. And it will return length of updated array. so while call on 2 nd time the sum is number not array .Thats why you got error
so should not reassign sum = sum.push
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 3, 4, 5, 6];
var sum = [];
for (var i = 0; arr1[i] < arr1.length; i++) {
for (var j = 0; arr2[j] < arr2.length; j++) {
sum.push(arr1[i] + arr2[j]);
}
}
console.log(sum);
I have 2 arrays. (arr1, arr2) I want to take the value at index 0 and
multiply it by each value in arr2, and add each value to a new row in
a 2D array.
ex.
arr1 = [1,3,5,7] arr2 = [4,2,1,6]
Outcome should be:
2Darray = [
[4,12,20,28],
[2,6,10,14],
[1,3,5,7],
[6,18,30,42]
];
Im having trouble with the for loop in javascript and how to create a
new row after each iteration. ```
Thanks
Using map like others said would be best.
Using the remainder operator(%) makes the most sense in my head:
const arr1 = [1,3,5,7];
const arr2 = [4,2,1,6];
var twoDemArray = [];
for (var i = 0; i < arr1.length; i++) {
let tempArr = [];
for (var j = 1; j < arr2.length+1; j++) {
let newNum = arr1[i]*arr2[j-1];
tempArr.push(newNum);
if (j % arr2.length == 0) {
twoDemArray.push(tempArr);
tempArr = [];
};
};
};
console.log(twoDemArray)
//do stuff with twoDemArray
Mapping over both arrays helps.
arr1 = [1,3,5,7];
arr2 = [4,2,1,6];
let res = arr2.map(a2 => arr1.map(a1 => a1*a2))
console.log(res);
You could map the arrays with the product of the values.
const
array1 = [1, 3, 5, 7],
array2 = [4, 2, 1, 6],
result = array2.map(v => array1.map(w => v * w));
result.map(a => console.log(...a));
console.log(result);
I encountered a problem!
for example! here is my 2 dimensional array: var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
and my desired outcome is : [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
the [6,9,12,15] came from adding the same index numbers of the previous inner arrays. (ex 1+2+3, 2+3+4, 3+4+5, 4+5+6 more clear : index 1 + index 1+ index1 produces 9)
I am so confused so far, the closes i did was to sum up [1,2,3,4][2,3,4,5][3,4,5,6], but I cant seem to do something with each and individual numbers :(
The question requested me to do nested for loops, So i cant use any thing like reduce, map, flatten, etc...
try with this way:https://jsfiddle.net/0L0h7cat/
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array4 = [];
for (j = 0; j < array[0].length; j++) {
var num =0;
for(i=0;i< array.length;i++){
num += array[i][j];
}
array4.push(num);
}
array.push(array4);
alert(array);
Just iterate over the outer array and the inner arrays and add the values to the result array array[3].
var array = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]];
array.forEach(function (a) {
a.forEach(function (b, i) {
array[3] = array[3] || [];
array[3][i] = (array[3][i] || 0) + b;
});
});
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
https://jsfiddle.net/0L0h7cat/
var array = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
];
var sumArr = [];
for (var i = 0; i < array[0].length; i++) {
sumArr[i] = 0;
for (var j = 0; j < array.length; j++)
sumArr[i] += array[j][i];
}
array.push(sumArr);
If you are interested in Arrow Functions, this will work:-
var array = [[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]];
var count = [];
array.forEach(x => x.forEach((y, i) => count[i] = (count[i] || 0) + y));
array.push(count);
console.log(array);
NOTE: Not cross browser support yet.
This is how -
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array2=[]
for (var i = array[0].length;i--;) {
var sum=0;
for (var j = array.length; j--;) {
sum=sum+array[j][i];
}
array2.push(sum)
}
array.push(array2.reverse());
document.write('<pre>'+JSON.stringify(array) + '</pre>');
But I'm sure there are more elegant methods. I'm just learning by answering questions myself.
A simplistic approach with just conventional for loops
var input = [[1,2,3,4],[2,3,4,5],[3,4,5,6]];
function getSumOfArrayOfArrays(inputArray) {
var length = inputArray.length;
var result = [];
for(var i=0; i<length; i++){
for(var j=0; j<=3; j++){
result[j] = result[j] ? result[j] + inputArray[i][j] : inputArray[i][j];
}
}
return result;
}
var output = getSumOfArrayOfArrays(input); // [6,9,12,15]
var desiredOutput = input;
desiredOutput.push(output)
document.write(JSON.stringify(desiredOutput));
// [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
I try to avoid writing nested for loops.
var arrayOfArrays=[
[1,2,3,4],
[2,3,4,5],
[3,4,5,6]
];
//define a function to extend the Array prototype
Array.prototype.add = function(otherArray){
var result = [];
for(var i = 0; i < this.length; i++) {
result.push( this[i] + otherArray[i] )
}
return result;
};
//reduce array of arrays to get the result array `sum`
var sum = arrayOfArrays.reduce(function(arrayA, arrayB){
//`arrayA`+`arrayB` becomes another `arrayA`
return arrayA.add(arrayB)
});
//put `sum` back to `arrayOfArrays`
arrayOfArrays.push(sum);
document.write('<pre>' + JSON.stringify(arrayOfArrays) + '</pre>');
I figured out a simple way to solve this, and it worked out.
var reverseArrayInPlace = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result.unshift(arr[i]);
}
for(var j = 0; j < result.length; j ++) {
arr[j] = result[j];
}
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//[5,4,3,2,1]
However, i'm wonder why can't I use an even simpler way by just assign the arr argument to the result value which is [5,4,3,2,1]? But the code below doesn't work, it still prints out [1,2,3,4,5].
var reverseArrayInPlace = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result.unshift(arr[i]);
}
arr = result;
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//[1,2,3,4,5]
Try this in your dev console:
var arr = [1,2,3];
function retArr(arr){
var res = arr;
res = [3,2,1];
return res;
}
retArr(arr); // returns 3,2,1
console.log(arr); // logs 1,2,3
All you did was create a new array!
Parameters of functions are pass-by-value.
the reason direct for-loop access works is because array properties are pass-by-reference.
P.S. an actual in-place reversal would look like this:
function reverseInPlace(array){
var swap = function(i,j){
var t = array[i];
array[i] = array[j];
array[j] = t;
};
for (var i = 0; i < array.length/2;i++){
swap(i,array.length-i-1);
}
}
Try using .slice(), .pop()
var reverseArrayInPlace = function(arr) {
var copy = arr.slice(0);
for (var n = 0; n < arr.length; n++) {
arr[n] = copy.pop();
}
return arr
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
Alternatively, using Array.prototype.sort()
var reverseArrayInPlace = function(arr) {
arr.sort(function(a, b, index) {
return index < index + 1 ? -1 : 1
});
};
//test
var arrayValue = ["a", "b", "c", "d", "e"];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
Let’s assume we have this two arrays:
x = [1, 2, 3];
y = ['a', 'b'];
What would be the best way to combine them and get the following result:
newArray = ['1a', '1b', '2a', '2b', '3a', '3b'];
Here is one way of doing that:
x.reduce(function(arr, x) {
return arr.concat(y.map(function(y) {
return x + y;
}));
}, []);
//=> ["1a", "1b", "2a", "2b", "3a", "3b"]
Try this:
var x = [1, 2, 3];
var y = ['a', 'b'];
var output = [];
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < y.length; j++) {
output.push(x[i]+y[j]);
}
}
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>
Try this..
var x = [1, 2, 3];
var y = ['a', 'b'];
var newarr = [];
for(var i=0;i<x.length;i++){
for(var j=0;j<y.length;j++){
newarr.push(x[i]+y[j]);
}
}
//alert(newarr);
DEMO
If arrow functions are supported you obtain the desired result like this:
[].concat.apply([],
x.map(x => y.map(y => x+y))
);
If not, you have to write it like this
[].concat.apply([],
x.map(function(x) { return y.map(function(y) {return x+y })})
);
Explanation:
The middle line yields the following result:
[ ["1a", "1b"], ["2a", "2b"], ["3a", "3b"] ]
Then the Array.prototype.concat method is used to concatenate the inner arrays.
You could simply create a array to be returned and do a simple loop for the array that contains numbers. Inside of that loop, you create another loop for the array of combinations to the numbers (var b=0,e=comb.length;e>b;b++). Using the i from the first loop (for(var i=0,l=array.length;l>i;i++)) you push the array at it (a[i]) with the array of combinations at the position b (c[b]) (inside of the loop that's inside of the first loop) to the new array. Finally, return the new array.
function CombineExample(a,c){
var New=[];
for(var i=0,l=a.length;l>i;i++){
for(var b=0,e=c.length;e>b;b++){
New.push(a[i]+c[b])
}
}
return New
}
Clean! And do this to use:
CombineExample([1,2,3],['a','b'])
/* returns ["1a", "1b", "2a", "2b", "3a", "3b"] */
Use nested loops to iterate all elements of the participating arrays. Populate new array elements inside the inner loop:
var x = [1, 2, 3];
var y = ['a', 'b'];
var newArray = [];
x.forEach(function(xItem) {
y.forEach(function(yItem) {
newArray.push(xItem.toString().concat(yItem));
});
});
console.log(newArray);
The simplest approach:
var x = ["a", "b", "c"];
var y = [1, 2, 3];
var newArray = [];
var i = 0;
for (;i < x.length;++i) {
var j = 0;
for (;j < y.length;++j) {
newArray.push(x[i] + y[j]);
}
}
;
Please do note that if both arrays are numeric, this will actually add the numbers, not concatenate. You'd need to do some string conversion.
var x = [1, 2, 3];
var y = ['a', 'b'];
var z = [];
for(var i=0;i<x.length;i++){
for(var j=0;j<y.length;j++){
z.push(x[i]+y[j]);
}
}
Are you seriously asking for that?