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);
Related
New to javascript. Need some guidance on the problem below:
I have these arrays:
array1 = [['a1'], ['a2'], ['a3']];
array2 = [['a1',4], ['a3',3], ['a6',2]];
How can i get the matching arrays whereby array1 first col = array2 first col?
Example expected result:
[['a1',4], ['a3',3]]
I hope the question makes sense. Not really sure how to approach this since the structure of these two arrays are different.
You can use filter to filter out the elements. Inside filter method check if elements exist in array1. You can flat array1 to check effeciently.
let flatArr1 = array1.flat(); //["a1", "a2", "a3"]
const result = array2.filter(([x,y]) => flatArr1.includes(x));
console.log(result) // for instance
This is my solution for your problem:
const compare = (array1, array2) => {
let matched = [];
const keys = [].concat(...array1);
for(let i = 0; i < array2.length; i++) {
for(let j = 0; j < array2.length; j++) {
let result = array2[i][j];
if(keys.includes(result)) {
matched.push(array2[i])
}
}
}
console.log("matched: ", matched);
};
I got 2 arrays
ArrayA = {"data":{"PlayerList":[{"Platform":1,"PlayerExternalId":205288,"Price":250,"RemainingTime":22},{"Platform":1,"PlayerExternalId":205753,"Price":10000,"RemainingTime":22}]}}
ArrayB = {"datafut": [{"currentPricePs4": "4149000","currentPriceXbox": "3328000","PlayerExternalId": "151152967"},{"currentPricePs4": "3315000","currentPriceXbox": "2720000","PlayerExternalId": "151198320"}]}
ArrayB is like a small database to compare prices. ArrayA needs theoretically an Interception with ArrayB. But this creates a new ArrayC which is complicated for me because I need the index of the results from ArrayA.
Moreover when comparing both array IDs, I need to compare both prices and calculate a difference into a variable so I can work with it later. How can I achieve this?
This is my pseudo code. Idk if this is even the right way..
Filter ArrayB by ArrayA //by playerID
for(
NewPrice = ArrayA.price / ArrayB.price + Index of ArrayA.price
index = Index of ArrayA.price)
Edit: or could I append the price from arrayB to arrayA and can calculate then somehow?
You can pass both arrays to following function: I have stored index, now if you only need index, you don't need to sort it otherwise I am sorting it on the base of index to keep the original order.
function mergeArrays(arrayA, arrayB) {
var players = arrayA.data.PlayerList;
var data = arrayB.data;
var arrayC = [];
for(let i=0; i<data.length; i++) {
var playerId = data[i].PlayerExternalId;
for(let j=0; j<players.length; j++) {
if(players[j].PlayerExternalId != playerId) {
continue;
}
var obj = {};
obj.playerId = playerId;
obj.index = j;
obj.price = players[j].price;
obj.xboxprice = data[i].currentPriceXbox;
obj.ps4price = data[i].currentPricePs4;
arrayC.push(obj);
}
}
arrayC.sort((a,b) => (a.index < b.index)?-1:(a.index>b.index?1:0));
return arrayC;
}
I'm trying to access elements from a JavaScript array:
[["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]]
I want to access
1, 2, 3, 4, 5, 6 separately in a variable and John, Rajan, Hitesh, Vin, Ritwik, Sherry separately in a variable.
I tried converting it to a string and split(), but it doesn't work.
this is code i tried
var jArray = <?php echo json_encode($newarray); ?> ;
var nJarr = jArray[0]; nJarr.toString();
var res = nJarr.split(","); var apname = res[0];
alert(apname);
but there's no alert appearing on the screen
If you are open to using Underscore, then it's just
var transposed = _.zip.apply(0, arr);
and the arrays you are looking for will be in transposed[0] and transposed[1].
You can write your own transpose function fairly easily, and it's more compact if you can use ES6 syntax:
transpose = arr => Object.keys(arr[0]).map(i => arr.map(e => e[i]));
>> transpose([["1","John"], ["2","Rajan"], ...]]
<< [[1, 2, ...], ["John", "Rajan", ...]]
If you want an ES5 version, here's one with comments:
function transpose(arr) { // to transpose an array of arrays
return Object.keys(arr[0]) . // get the keys of first sub-array
map(function(i) { // and for each of these keys
arr . // go through the array
map(function(e) { // and from each sub-array
return e[i]; // grab the element with that key
})
))
;
}
If you prefer old-style JS:
function transpose(arr) {
// create and initialize result
var result = [];
for (var i = 0; i < arr[0].length; i++ ) { result[i] = []; }
// loop over subarrays
for (i = 0; i < arr.length; i++) {
var subarray = arr[i];
// loop over elements of subarray and put in result
for (var j = 0; j < subarray.length; j++) {
result[j].push(subarray[j]);
}
}
return result;
}
Do it like bellow
var arr = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var numbers = arr.map(function(a){return a[0]}); //numbers contain 1,2,3,4,5
var names = arr.map(function(a){return a[1]}); //names contain John,Rajan...
Try this:
var data = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var IDs = [];
var names = [];
for(i=0; i<data.length; i++)
{
IDs.push(data[i][0]);
names.push(data[i][1]);
}
console.log(IDs);
console.log(names);
Here is the working fiddle.
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]);
}
I'm iterating over array couples and I need to sort one by the order of the other.
Say I have these two arrays:
aLinks = [4,5,6]
bLinks = [1,2,3,4,5,6]
I need to return:
aLinks = [4,5,6]
bLinks = [4,5,6,1,2,3]
meaning that i need to have the items that match first array first and than the rest,
sorted by order if possible.
I'm working with d3 so I'm using forEach to go through the link sets and save the order of aLinks.
I don't know how to apply this order to bLinks
var linkOrder = [];
linkSets.forEach(function(set, i) {
linkOrder = [];
set.aLinks.forEach(function(link,i){
linkOrder.push(link.path);
})
});
You can do it like:
Take out the matching items from second array into a temp array
Sort the temp array
Sort the second array containing only items that did not match
Concatenate the second array into the temp array
Code - With the fix provided by User: basilikum
var first = [4,5,6];
var second = [1,7,3,4,6,5,6];
var temp = [], i = 0, p = -1;
// numerical comparator
function compare(a, b) { return a - b; }
// take out matching items from second array into a temp array
for(i=0; i<first.length; i++) {
while ((p = second.indexOf(first[i])) !== -1) {
temp.push(first[i]);
second.splice(p, 1);
}
}
// sort both arrays
temp.sort(compare);
second.sort(compare);
// concat
temp = temp.concat(second);
console.log(temp);
Working Demo: http://jsfiddle.net/kHhFQ/
You end up with A + sort(A-B) - so you just need to compute the difference between the 2 arrays. Using some underscore convenience methods for example:
var A = [4,5,6];
var B = [1,2,3,4,5,6];
var diff = _.difference(A,B);
var result = _.flattern(A, diff.sort());
iterate the first array, removing the values from the second array and then appending them to the start of the array to get the right order :
var arr1 = [4,5,6];
var arr2 = [1,2,3,4,6,5];
arr1.sort(function(a,b) {return a-b;});
for (i=arr1.length; i--;) {
arr2.splice(arr2.indexOf(arr1[i]), 1);
arr2.unshift( arr1[i] );
}
FIDDLE