merge unknown number of sub-arrays in array - javascript

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

Related

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

Convert every nth element of an array to an object in javascript

I'd like to convert:
var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"]
into:
var rows = [
[1, "Shaw", "Tanzania"],
[2, "Nelson", "Kazakhstan"],
[3, "Garcia", "Madagascar"]
];
I've seen this answer to a similar question, but I don't understand how that works and extend it to every nth element
Use a for loop with Array#slice. You iterate the original array using the require chunk size as the step. On each iteration you slice the relevant part from the original array (slice doesn't mutate the array), and push it into the result array.
var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"];
var result = [];
var chunkSize = 3;
for(var i = 0; i < people.length; i+= chunkSize) {
result.push(people.slice(i, i + chunkSize));
}
console.log(result);

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

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)

splitting array elements in javascript split function

Hi i have the below array element
var array =["a.READ","b.CREATE"]
I'm trying to split the elements based on "." using javascript split method
below is my code
var array1=new Array();
var array2 = new Array();
for (var i = 0; i < array .length; i++) {
array1.push(array [i].split("."));
}
console.log("this is the array1 finish ----"+array1)
The out put that i'm receiving is
[["a","READ"],["b","CREATE"]]
The expected output that i want is
array1 =["a","b"]
array2=["READ","CREATE"]
I'm stuck here any solution regarding this is much helpful
You need to add to array2 and use both elements from the returned array that String.prototype.split returns - i.e. 0 is the left hand side and 1 is the right hand side of the dot.
var array = ["a.READ", "b.CREATE"]
var array1 = []; // better to define using [] instead of new Array();
var array2 = [];
for (var i = 0; i < array.length; i++) {
var split = array[i].split("."); // just split once
array1.push(split[0]); // before the dot
array2.push(split[1]); // after the dot
}
console.log("array1", array1);
console.log("array2", array2);
We'll start off with a generic transpose function for two-dimensional arrays:
function transpose(arr1) { // to transpose a 2d array
return arr1[0].map( // take the first sub-array and map
function(_, i) { // each element into
return arr1.map( // an array which maps
function(col) { // each subarray into
return col[i]; // the corresponding elt value
}
);
}
);
}
Now the solution is just
transpose( // transpose the two-dimensional array
array.map( // created by taking the array and mapping
function(e) { // each element "a.READ" into
return e.split('.'); // an array created by splitting it on '.'
}
)
)
You are adding nothing to array2. Please use indexes properly , like below:
var array1=new Array();
var array2 = new Array();
for (var i = 0; i < array .length; i++) {
array1.push(array [i].split(".")[0]);
array2.push(array [i].split(".")[1]);
}
you can do something like this
var array =["a.READ","b.CREATE"];
var arr1= [], arr2= [];
array.forEach(function(item,index,arr){
item.split('.').forEach(function(item,index,arr){
if(index % 2 === 0){
arr1.push(item);
}else{
arr2.push(item);
}
});
});
console.log(arr1);
console.log(arr2);
DEMO
I guess this is a bit redundant but, the split method actually returns and array. Although your code was off you were not modifying array2. Consider the following.
var array = [ "a.READ" , "b.CREATE" ]
, array1 = []
, array2 = []
// cache array length
, len = array.length;
for ( var i = 0; i < len; i++ ) {
// the split method returns a new array
// so we will cache the array
// push element 0 to array1
// push element 1 to array2
var newArr = array[ i ].split('.');
array1.push( newArr[ 0 ] );
array2.push( newArr[ 1 ] );
}
console.log( 'array1: ', array1 );
console.log( 'array2: ', array2 );
Use this:
for (var i = 0; i < array .length; i++) {
var parts = array[i].split('.');
array1.push(parts[0]);
array2.push(parts[1]);
}
You have not assigned any value to Array2. You can do as shown below.
var array1=[];
var array2 = [];
for (var i = 0; i < array .length; i++) {
var arrayTemp=[];
arrayTemp.push(array [i].split("."));
array1.push(arrayTemp[0]);
array2.push(arrayTemp[1]);
}

How to extract values from an array of arrays in Javascript?

I have a variable as follows:
var dataset = {
"towns": [
["Aladağ", "Adana", [35.4,37.5], [0]],
["Ceyhan", "Adana", [35.8,37], [0]],
["Feke", "Adana", [35.9,37.8], [0]]
]
};
The variable has a lot of town data in it. How can I extract the first elements of the third ones from the data efficiently? I,e, what will ... be below?
var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data
And what to do if I want to store both values in the array? That is
var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data
I'm very new to Javascript. I hope there's a way without using for loops.
On newer browsers, you can use map, or forEach which would avoid using a for loop.
var myArray = dataset.towns.map(function(town){
return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]
But for loops are more compatible.
var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
myArray.push(dataset.towns[i][2];
}
Impossible without loops:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2][0]);
}
// at this stage myArray = [35.4, 35.8, 35.9]
And what to do if I want to store both values in the array?
Similar, you just add the entire array, not only the first element:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2]);
}
// at this stage myArray = [[35.4,37.5], [35.8,37], [35.9,37.8]]

Categories

Resources