How to extract values from an array of arrays in Javascript? - 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]]

Related

Generating an array with sub-arrays

I realize this is a somewhat off manner of operations, but for the sake of possibility, I'm wondering if anyone can help?
Here array2 is holding the end state I would like array1 to hold (only I want to do it with the for loop. It's fine that each sub_array's have to be initialized as their own variables, I'm just trying to get the array1 to hold N number of sub_arrays via the loop.
Here is the example I've tried, but trying to "compile" it via a string doesn't allow the sub_arrays to be called in a useable manner.
var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []
var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]
for (var i = 0; i < numberOfSubArrays; i++) {
array1[i] = "sub_array" + i
}
Any thoughts would be much appreciated!
var numberOfSubArrays = 3
var sub_array1 = [1]
var sub_array2 = [2]
var sub_array3 = [3]
var array1 = []
// we don't need array2 at all
//var array2 = [sub_array1,sub_array2,sub_array3]
// you need to count from 1..n, as you named your sub_arrays like that
for (var i = 1; i <= numberOfSubArrays; i++) {
// you can use eval, but be careful, eval is evil!
array1[i-1] = eval("sub_array" + i)
}
console.log(array1);
Using eval is yucky. This will work in browsers:
var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []
var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]
for (var i = 0; i < numberOfSubArrays; i++) {
array1[i] = window["sub_array" + i + 1];
}
In browsers, "global" vars are really objects in "window".
Note: this will not work in tools like jsfiddle, because they put your code inside a function (that you don't see).

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

How to access elements of arrays within array (JavaScript)?

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.

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 do I divide a complex string into 3 seperate arrays?

Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values
mystring = 4|black|cat, 7|red|dog, 12|blue|fish
Here's where I want to be:
I want to end up with three arrays.
array1=("4","7","12")
array2=("black","red","blue")
array3=("cat","dog","fish")
I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.
I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:
var arr1 = [], arr2 = [], arr3 = [],
mystring = "4|black|cat, 7|red|dog, 12|blue|fish";
mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) {
arr1.push($1);
arr2.push($2);
arr3.push($3);
});
Example
You want to use the split() method :
var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]
//etc...
Like this?:
var values = mystring.split(',');
var arrays = new Array();
for(var i=0; i < values.length; i++) {
var parts = values[i].split('|');
for(var j = 0; j < parts.length;j++) {
if(!arrays[j]) {
arrays[j] = new Array();
}
arrays[j].push(parts[j]);
}
}
Will give you an array that contains those three arrays.
var str = '4|black|cat, 7|red|dog, 12|blue|fish';
var tmp = str.split(',');
var firstArray = Array();
var secondArray = Array();
var thirdArray = Array();
for( var i in tmp ){
var splitted = tmp[i].split('|');
//alert(true);
firstArray[i]=splitted[0];
secondArray[i]=splitted[1];
thirdArray[i]=splitted[2];
}

Categories

Resources