Why this array producer code doesn't work as it shows? - javascript

I have used some code as bellow to produce new array from tow arrays :
var arr1 = [['wo','ss'],['er','me'], ['lo','to']];
var arr2 = [['mine','yours'],['from', 'theme']];
var arr3 = [];
var temp = [];
//this will be an array of arrays that every index is arr2 + one index from arr1
var end = [];
arr1.forEach(function(item) {
temp = arr2;
temp.push(item);
end.push(temp);
})
console.log(end)
But after the result is not my desired and is not logical
[
['mine','yours'], ['from','theme'], ['wo', 'ss'],
['mine', 'yours], ['from','theme'], ['er', 'me'],
['mine', 'yours], ['from','theme'], ['lo', 'to']
]

You must clone the arr2 for each iteration defining temp as new array each time
var arr1 = [['wo','ss'],['er','me'], ['lo','to']];
var arr2 = [['mine','yours'],['from', 'theme']];
var arr3 = [];
var end = [] //this will be an array of arrays that every index is arr2 + one index from arr1
arr1.forEach(function(item) {
var temp = arr2.slice();
temp.push(item);
end.push(temp);
})
console.log(end);
This code works as you expected

In your code Array#push method will push values to arr2 which update the array(since temp is reference to array arr2) on each iteration.
Use Array#concat method which generates a new concatenated array although Array#map can be used for generating the array.
var arr1 = [
['wo', 'ss'],
['er', 'me'],
['lo', 'to']
];
var arr2 = [
['mine', 'yours'],
['from', 'theme']
];
var end = arr1.map(function(item) {
return arr2.concat([item]);
})
console.log(JSON.stringify(end))
UPDATE : Currently it creates the reference to the parent array updating one will change other. if you want a new array with the element then do it with Array#map and Array#slice methods .
var arr1 = [
['wo', 'ss'],
['er', 'me'],
['lo', 'to']
];
var arr2 = [
['mine', 'yours'],
['from', 'theme']
];
var end = arr1.map(function(item) {
return arr2.map(function(v) {
return v.slice();
}).concat([item.slice()]);
})
console.log(end)

Related

Empty all elements in array with pop method

I am trying to empty an array by using the pop method after that I want to push the returned result of the pop method to another array and get the full result, but the pop method doesn't satisfy my needs it always stops midway what is the problem?
let arr = [1,2,3,4,5,6,7]
let newArr = []
//console.log(arr.pop())
const fib = function(n){
if(n <= arr.length){
newArr.push(arr.pop())
return fib(n+1)
}
}
fib(0)
console.log(newArr)
I would do like that:
var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = [];
while(myArr.length){
myNewArr.push(myArr.pop());
}
console.log(myArr, myNewArr);
If you just want to reverse it you could use the reverse function for Arrays:
var myArr = [1,2,3,4,5,6,7,8,9];
myArr = myArr.reverse();
console.log(myArr);
// Or if you really need 2 variables and one needs to be empty
var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = myArr.reverse();
myArr = [];
console.log(myArr, myNewArr);
let arr = [1,2,3,4,5,6,7]
let newArr = []
//console.log(arr.pop())
const fib = function(n){
if(!n <= 0){
newArr.push(arr.pop())
return fib(n-1)
}
}
fib(arr.length)
console.log(newArr)
If you want your array empy... I think this is the easiest way.
var array = [1,2,3,4,5,6,7]
array = []
console.log(array)

change array index in for loop before push in javascript

var array = [23,34,56,35]
I want to do this using a for loop in javascript
var array = [
2:23
3:34
4:56
5:35
]
instead of
var array = [
0:23
1:34
2:56
3:35
]
You can use forEach of array, to do:
var array = [23,34,56,35];
var result = [];
array.forEach((current,index)=>{
result[index+2] = current;
});
console.log(result);

push more than one elements at same index in array

how to push more than one element at one index of a array in javascript?
like i have
arr1["2018-05-20","2018-05-21"];
arr2[5,4];
i want resulted 4th array to be like:
arr4[["2018-05-20",5],["2018-05-21",4]];
tried pushing like this:
arr1.push("2018-05-20","2018-05-21");
arr1.push(5,4);
and then finally as:
arr4.push(arr1);
But the result is not as expected. Please someone help.
Actually i want to use this in zingChart as :
Options Data
Create an options object, and add a values array of arrays.
Calendar Values
In each array, provide the calendar dates with corresponding number values in the following format.
options: {
values: [
['YYYY-MM-DD', val1],
['YYYY-MM-DD', val2],
...,
['YYYY-MM-DD', valN]
]
}
Your question is not correct at all, since you cannot push more than one element at the same index of an array. Your result is a multidimensional array:
[["2018-05-20",5],["2018-05-21",4]]
You have to create a multidimensional array collecting all your data (arrAll)
Then you create another multidimensional array (arrNew) re-arranging previous data
Try the following:
// Your Arrays
var arr1 = ["2018-05-20","2018-05-21"];
var arr2 = [5, 4];
//var arr3 = [100, 20];
var arrAll = [arr1, arr2];
//var arrAll = [arr1, arr2, arr3];
// New Array definition
var arrNew = new Array;
for (var j = 0; j < arr1.length; j++) {
var arrTemp = new Array
for (var i = 0; i < arrAll.length; i++) {
arrTemp[i] = arrAll[i][j];
if (i === arrAll.length - 1) {
arrNew.push(arrTemp)
}
}
}
//New Array
Logger.log(arrNew)
Assuming the you want a multidimensional array, you can put all the input variables into an array. Use reduce and forEach to group the array based on index.
let arr1 = ["2018-05-20","2018-05-21"];
let arr2 = [5,4];
let arr4 = [arr1, arr2].reduce((c, v) => {
v.forEach((o, i) => {
c[i] = c[i] || [];
c[i].push(o);
});
return c;
}, []);
console.log(arr4);

merge unknown number of sub-arrays in array

I have an array like this:
arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]
and I want to turn it into an array like this:
arr = [ [x,x],[x,x] , [x,x],[x,x],[x,x], [x,x] ]
so I have tried this:
for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }
but it does not work. How can I 'merge' this intermediate level of array?
With ES6 you can use spread syntax with concat()
var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]
var merged = [].concat(...arr)
console.log(JSON.stringify(merged))
For older versions of ecmascript the same can be done using concat() and apply().
var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]
var merged = [].concat.apply([], arr)
console.log(JSON.stringify(merged))
The array.concat() doesn't change the array you call it on, but rather returns a new array - a new array you are ignoring.
You should create a result array and then append everything to that, instead of trying to modify arr.
var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ];
var new_arr = [];
for(var i = 0; i < arr.length; i++){
new_arr = new_arr.concat(arr[i]);
}

How to display the array?

I have 3 arrays:
Array1 and Array2 have connections to each other:
var Array1 = ['Bob','James','Kanye','West'];
var Array2 = [0,1,2,3];
var Array3 = [1,3,0,2];
How do I display it to this?
Array4 = ['James', 'West', 'Bob','Kanye'];
you will require 2 loops, 1 will go through each element of Array3 and Second loop will be used to find the index value will be compared with Array2 to find index of Array 1 and then that index value will be saved in Array4 from Array1
for (var i = 0; i < Array3.length; i++)
{
var index = Array3[i];
var position=-1;
for(var j=0; j < Array2.length;j++)
{
if(index==Array2[j])
{
position = j;
break;
}
}
Array4[i] = Array1[j];
}
You need to run a loop over Array, take the integer inside as indexnumber, then you print out the first array with the numbers you just took from the first array.
You need to use -- and read the documentation for -- arrays' map method:
const names = ['Bob','James','Kanye','West'];
const order = [1,3,0,2];
const orderedNames = order.map(x => names[x]);
console.log(orderedNames);
// => ["James", "West", "Bob", "Kanye"]
Fiddle: https://jsfiddle.net/68hrrjx3/
Also kinda relevant in the context of the other answers: What is the difference between declarative and imperative programming

Categories

Resources