Pushing value into a multidimensional array - javascript

I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [
{
'a':10,
'b':20,
'c':30
},
{
'a':1,
'b':2,
'c':3
},
{
'a':100,
'b':200,
'c':300
}];
Now , i need a multidimensional array like
var values = [[10,1,100], //a
[20,2,200], //b
[30,3,300]]; //c
What i have tried is
var values = [];
for(var key in data[0])
{
values.push([]); // this creates a multidimesional array for each key
for(var i=0;i<data.length;i++)
{
// how to push data[i][key] in the multi dimensional array
}
}
Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. Even i don't want to use extra for loops
If you guys found any duplicate here , just put the link as comment without downvote

Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}

Related

How do i split up an array that holds an array?

Hello my fellow JS friends,
I am letting a user import a csv file (excel sheet) and i convert that into
an array. which has 472 rows and 87 columns in this case.
so my array looks like this:
and everything is separated by commas like a usual array.
The issue is I need to separate the array within the array and when i do that i get an array with the length of 9 million, which i think is wrong
vm.allTextLines = files.split(/\r\n|\n/);
var headers = vm.allTextLines[0].split(',');
vm.columnCount = headers.length;
vm.rowCount = vm.allTextLines.length - 1;
for (var i = 0; i < vm.allTextLines.length; i++) {
// split content based on comma
var data = vm.allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
vm.lines.push(tarr);
}
}
//this is where i split the array that contains the csv
//data and put it into its own array I believe this is
//where the issue is.
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
}
If you can help me correct this for each I would appreciate it alot.
Thank you in advance guys!
I agree with you about the place of error, because it seems you nested the loop in a wrong way. Following a snippet where you can check what I mean.
i.e:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
// Here you should not nest the loop
for(var i=1;i<vm.allTextLines.length; i++){
vm.uniqueAll.push(vm.allTextLines[i].split(','));
}
for(var j=0; j < vm.uniqueAll.length; j++){
for(var r =0; r < vm.uniqueAll[j].length; r++){
vm.arrayOfValuesOfFile.push(vm.uniqueAll[j][r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
Of Course you could easily optimize the algorithm:
let vm = {
allTextLines:['h1,h2,h3','row1val1,row1val2,row1val3', 'row2val1,row2val2,row2val3'],
uniqueAll: [],
arrayOfValuesOfFile:[]
}
for(var i=1;i<vm.allTextLines.length; i++){
let currentLinesValue = vm.allTextLines[i].split(',');
vm.uniqueAll.push(currentLinesValue);
for(var r =0; r < currentLinesValue.length; r++){
vm.arrayOfValuesOfFile.push(currentLinesValue[r]);
}
}
console.log('allTextLines', vm.allTextLines);
console.log('uniqueAll', vm.uniqueAll);
console.log('arrayOfValuesOfFile', vm.arrayOfValuesOfFile);
First you should transform you bidimensional array into a one-dimension array.
var allTogether = []; // Array with all your CSV (no matter from which file it came from)
for (var i = 0; vm.allTextLines.length; i++) {
allTogether.push(vm.allTextLines[i]); // Gets the CSV line an adds to a one-dimension array
}
// Now you can iterate over the one-dimension array
for (var i = 0; allTogether.length; i++) {
var csvFields = allTogether[i].split(',');
// Here goes your code that works with the CSV fields.
}

splitting a string based on delimiter using javascript

Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.

loop different arrays javascript

Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.

Handling multidimentional array in java script is not working

function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed

Compare arrays with jQuery [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Simplest code for array intersection in javascript
How to merge two arrays in Javascript
There are three arrays:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_new = Array();
First one is general, second is the items currenly in use. Third one includes all the items from the first array, witch are not mentioned in second.
How do I remove from the first array items, witch are used in second, and write the result to the third array?
We should get items_new = Array(523, 334, 5346). 3452 and 31 are removed, because they are mentioned in second array.
You could do this:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_compared = Array();
$.each(items, function(i, val){
if($.inArray(val, items_used) < 0)
items_compared.push(val);
});
That's it
Why not a simple for loop?
for(var j = 0; j < items.length; j++)
{
var found = false;
for(var k = 0; k < items_used.length; k++)
{
if(items_used[k] == items[j])
{
found = true;
break;
}
}
if(!found)
items_compared.push(items[j]);
}
As a faster solution maybe :
var j, itemsHash = {};
for (j = 0; j < items.length; j++) {
itemsHash[items[j]] = true;
}
for (j = 0; j < itemsUsed.length; j++) {
itemsHash[itemsUsed[j]] = false;
}
for (j in itemsHash) {
if (itemsHash[j]) {
itemsCompared.push(j);
}
}
runs in O(n) time, with a little more memory.
Basically I would make the third have all elements in the first, then loop through the second array removing all of those elements found in the first.
var items_compared = items;
for(int i = 0; i < items_used.length; ++i)
{
var indx = $.inArray(items_used[i], items_compared);
if(indx != -1)
items_compared.splice(indx, 1);
}

Categories

Resources