javascript - multidimensional array contains 4 items but length indicates: 0 - javascript

I made a multidimensional array today which creates 4 new arrays within the first array. when I console.log my array it says that there are 0 items in it, but i do see my 4 arrays each with other items. See the console.log below for a clearer image:
vm.allGroupsInClassifications = [];
datacontext.graph.getAllGroups().then(function (data) {
var groups = [];
// get all clasification names and put them in the array and create a new array
for (var k in vm.classificationNames) {
var groupName = vm.classificationNames[k];
groups[groupName] = new Array();
}
// go through all the groups and sort them based on their classification
for (var i = 0; i < data.length; i++) {
if (data[i].classification != null) {
modifyGroupContent(data[i], groups, 0);
}
else if (data[i].classification == null)
modifyGroupContent(data[i], groups, 1);
}
vm.allGroupsInClassifications = groups;
console.log(vm.allGroupsInClassifications);
any help would be appreciated. Cheers!

Because you have no indexes. groups[groupName] = new Array(); won't add an item to your array, because all your groupName variables are not numbers. And thus you have an array-object-like thing.
If your groupName's were say 0,1,2 and 3, when you console.log the object, you will get the last number+1 (in this case 4).
Here you can access your arrays with the keys - so in this case vm.allGroupsInClassifications['Confidential'] will return your array.
But since you don't have actual numeric indexes, the length of your object-array thing is 0.
Hope you understand

It's because your array is incorrect. You have an array with keys :
[
"Algemeen" : [...],
"Confidential" : [...]
]
This is incorrect, as arrays can't have keys. Javascript being Javascript, it allows you to define it nonetheless, but when you ask for its length, it's quite unable to answer and says 0. It should be an object :
{
"Algemeen" : [...],
"Confidential" : [...]
}
If you really want to keep an array of arrays, remove the keys :
[ [...],[...] ]
Now the length is 2.

Related

Puh array in empty array that create before

I push two Array in one Array But can't use them as a string,This result in bellow about two arrays in one array :
Array(0) [] //This is empty array that I create before and push these two array bellow to them
length:2
0:Array(1) ["cfdb9868-0f69-5781-b1e4-793301280788"]
1:Array(1) ["cfdb9868-0f69-5781-b1e4-793301280788"]
and I create a for for access them but I can ! I write this code "
for(var index = 0 ; index < Array.length ; ++index) {
let Each_String_In_Brackets = Array[index] ;
console.log(Each_String_In_Bruckets);
}
Why is this happen!
I mean Why when we push array in empty array can't access them!
I want to access the content of them, I have a string In each bracket.
var arr = [];
arr.push(["cfdb9868-0f69-5781-b1e4-793301280788"]);
arr.push(["cfdb9868-0f69-5781-b1e4-793301280788"]);
//assuming inside array always will be one element:
arr.forEach((item)=>{ console.log(item[0])})
//if inside array may be multiple elements, then use this
arr.forEach((item, index)=>{
item.forEach((child)=>{ console.log(child)})
})
pushing a full array into another array makes it a 2D array ( at the indexes where you push another array ) so for example if I have the first array
BArray[]
But if I push another array into it
BArray2 = [1,2,3,4];
BArray.push(Array2);
We would not be able to access it just by
BArray[0]
This would return the entire array2 rather the content of array2 at index 0.
Therefore you would do this
BArray[0][0]
So this would give us ( from your array ) "cfdb9868-0f69-5781-b1e4-793301280788"
If you would like to just dump out the content of BArray2 into BArray
You can use the spread operator.
BArray[...BArray2];
( Also I would not use Array as variable name ! It can be confusing as new Array(10); is a way of creating arrays and having arrays with that name isn't best practice ! )
Hope this helps !
You are pushing array in array, so you must access as 2D array:
var array = [];
var arrayString1 = ["StringInArray1"],
arrayString2 = ["StringInArray2"];
array.push(arrayString1);
array.push(arrayString2);
console.log(JSON.stringify(array));
array.forEach(arrayItem => {
console.log("StringInArray: " + arrayItem[0]);
})
Or maybe you want to append array:
var array = [];
var arrayString1 = ["StringInArray1"],
arrayString2 = ["StringInArray2"];
[].push.apply(array, arrayString1);
[].push.apply(array, arrayString2);
console.log(JSON.stringify(array));
array.forEach(arrayItem => {
console.log("StringInArray: " + arrayItem);
})

How to initialize 4d array in javascript?

Here is my code:
var arr = [[[[[]]]]];
var c = 20;
for (i=0;i<5;i++)
arr[i][0][0][0] = c;
alert(arr[2][0][0][0]);
It doesn't work, but how can I do this?
Most people here are using for loops, which I think are mostly obsolete in the age of anonymous functions in JavaScript. You people should know better :P
Anyway, you can solve this quite nicely in a one-liner. Here are a few scripts that can initialize your array...
If you already have a 4-dimensional array, you can initialize it elegantly like this:
arr.forEach(function(e) { e[0][0][0] = c })
Or, if you're more into map:
arr.map(function(e) { e[0][0][0] = c })
These are assuming you already have c defined, which you do in your code sample (20).
From now on, though, please Google your questions before asking them on stackoverflow. You will receive an answer that has already been accepted :)
It doesn't work because you haven't specified any elements beyond the first one, so the length of array is one and accessing further keys is incorrect.
I think, the most convenient way would be to push a new 3d array with c inside on every iteration (actually I have no idea what you're trying to achieve with this xD):
var arr = [];
var c = 20;
for (i=0;i<5;i++)
arr.push([[[c]]])
alert(arr[2][0][0][0]);
(in your example it's actually 5d, but as you've asked for 4d, writing 4d there)
It is unclear what you want, but I imagine a 4 dimension array is an array that has a set of arrays nested 3 deep, each of which has an array nested 2 deep, each of which has a single array that contains values.
In a one dimension array, you access the value at index 2 by:
arr[2];
In a two dimension array, you'd access the value at (2,3) by:
arr[2][3]
and so on until you get to the value at (2,3,1,2) in a four dimension array by:
arr[2][3][1][2]
and if that was the only value in the array, it would look like:
[,,[,,,[,[,,'value at 2312']]]];
If there was also a value at (1,1,0,2) the array would now look like:
[,[,[[,,'value at 1102']]],[,,,[,[,,'value at 2312']]]];
There can only be values in the last nested array, the value at indexes in every other array must be another array (for the lower dimensions), so to insert at value at, say (2,1,3,1) and assign it a value of 6, you need to loop over the array and inspect each index. If it's not already an array, insert an array and keep going, e.g.:
// Insert value in arrary at coord
// coord is a comma separated list of coordinates.
function insertValue( array, coord, value) {
var coords = coord.split(',');
var arr = array;
for (var c, i=0, iLen=coords.length-1; i < iLen; i++) {
c = coords[i];
if (!Array.isArray(arr[c])) arr[c] = [];
arr = arr[c];
}
arr[coords[i]] = value;
return array;
}
document.write('result: ' + JSON.stringify(insertValue([],'1,2,1,3','at 1213')));
I don't understand what you are trying to do in the OP: are you trying to create a value of 20 at coordinates (0,0,0,0), (1,0,0,0), (2,0,0,0), etc.? If that is the case, you also need a fill function that will iterate for the required number of times and pass suitable arguments to insertValue.
If that's what you want, then given the above you should be able to write such a function. On the first iteration it would pass:
insertValue(array, '0,0,0,0', 20)
and on the second:
insertValue(array, '1,0,0,0', 20)
and so on. You may wish to modify the function so that instead of the coords being a CSV string, you pass an array like [0,0,0,0] (which is what split turns the CSV string into), but that's up to you.
Note that you must pass all 4 dimensions, otherwise you will replace one of the dimension arrays with a value and effectively delete all other points in that dimension sector.
PS
ES5 introduced forEach, which helps encapsulate loops but doesn't necessarily mean less code, or faster execution, than an equivalent for loop:
// Insert value in arr at coord
// coord is a comma separated list of coordinates.
function insertValue( array, coord, value) {
var arr = array;
var coords = coord.split(',');
var last = coords.pop();
coords.forEach(function(c) {
if (!Array.isArray(arr[c])) arr[c] = [];
arr = arr[c];
})
arr[last] = value;
return array;
}
Create array with 5 nested arrays:
var arr = [[[[[]]]], [[[[]]]], [[[[]]]], [[[[]]]], [[[[]]]], [[[[]]]]];
var c = 20;
for (i=0;i<5;i++)
arr[i][0][0][0] = c;
alert(arr[2][0][0][0]);
EDIT: if you dig into functional programming and recursion, you can initialize your multidimensional array with just a few lines of code. Let's say you want 4-dimensional array with length 10 of each dimension:
function createNDimensionalArray(n, length) {
return n === 1
? new Array(length)
: Array.apply(null, Array(length)).map(createNDimensionalArray.bind(null, n - 1, length));
}
var arr = createNDimensionalArray(4, 10);
console.log(arr); // creates 4-dimensional array 10x10x10x10
Notice that initialization like this could be very slow if you create very big arrays (e.g. createNDimensionalArray(5, 10000).
If you prefer to set length of each dimension, you can modify previous the solution like this:
function createNDimensionalArray(dims) {
return dims.length === 1
? new Array(dims[0])
: Array.apply(null, Array(dims[0])).map(createNDimensionalArray.bind(null, dims.slice(1)));
}
var arr = createNDimensionalArray([2, 3, 4, 5]);
console.log(arr); // creates 4-dimensional array 2x3x4x5

Javascript: Find douplicated values from array with keys

Title is pretty much self explanatory...
I want to be able to find duplicated values from JavaScript array.
The array keys can be duplicated so I need to validate only the array values.
Here is an example :
var arr=[
Ibanez: 'JoeSatriani',
Ibanez: 'SteveVai',
Fender: 'YngwieMalmsteen',
Fender: 'EricJohnson',
Gibson: 'EricJohnson',
Takamine: 'SteveVai'
];
In that example:
the key is the guitar brand
the value is the guitar player name.
So:
If there is duplicated keys (like: Ibanez or Fender) as on that current example that is OK :-)
But
If there is duplicated values (like: EricJohnson or SteveVai) I'm expecting to get (return) that error:
EricJohnson,SteveVai
You can't have associative arrays in Javascript. You can create an array of objects, like:
var arr=[
{Ibanez: 'JoeSatriani'},
{Ibanez: 'SteveVai'},
{Fender: 'YngwieMalmsteen'},
{Fender: 'EricJohnson'},
{Gibson: 'EricJohnson'},
{Takamine: 'SteveVai'}
];
Then you'll need a for...in loop to go over every object in the array, create a new array of values and check that for duplicates, which is also not very straightforward - basically you'll want to sort the array and make sure no value is the same as the one after it.
var arrayOfValues = [];
arr.forEach(function(obj){
for(var prop in obj)
arrayOfValues.push(obj[prop]);
});
arrayOfValues.sort(); // by default it will sort them alphabetically
arrayOfValues.forEach(function(element,index,array){
if(array[index+1] && element==array[index+1])
alert("Duplicate value found!");
});
First of all, object keys can not be repeated.
This means that:
({
"Fender": "Jim",
"Fender": "Bob"
})["Fender"]
Would simply return: "Bob".
However, I did make a code that could allow you to find duplicates in values, but as I said, the key will have to be unique:
var arr = {
Ibanez: 'EricJohnson',
Fender: 'YngwieMalmsteen',
Gibson: 'EricJohnson',
Takamine: 'SteveVai',
"Takamine2": 'SteveVai'
};
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
var track = [];
var exists = [];
for (var val in arr) {
if (contains(track, arr[val])) {
exists.push(arr[val]);
} else {
track.push(arr[val])
}
}
alert(exists)
You can see it working here: http://jsfiddle.net/dr09sga6/2/
As others have commented, the example array you provided isn't a valid JavaScript array. You could, however, keep a list for each guitar type:
var mapping = {
Ibanez: ['JoeSatriani','SteveVai'],
Fender: ['YngwieMalmsteen','EricJohnson']
Gibson: ['EricJohnson'],
Takamine: ['SteveVai']
];
Or a list of each guitar/musician pair:
var pairs = [
['Ibanez','JoeSatriani'],
['Ibanez','SteveVai'],
['Fender','YngwieMalmsteen'],
['Fender','EricJohnson'],
['Gibson','EricJohnson'],
['Takamine','SteveVai']
];
Your solution is going to depend on which pattern you go with. However, in the second case it can be done in one chained functional call:
pairs.map(function(e) {return e[1]}) // Discard the brand names
.sort() // Sort by artist
.reduce(function(p,c,i,a){
if (i>0 && a[i]==a[i-1] && !p.some(function(v) {return v == c;})) p.push(c);
return p;
},[]); //Return the artist names that are duplicated
http://jsfiddle.net/mkurqmqd/1/
To break that reduce call down a bit, here's the callback again:
function(p,c,i,a){
if (i>0
&& a[i]==a[i-1]
&& !p.some(function(v) {
return v == c;
}))
p.push(c);
return p;
}
reduce is going to call our callback for each element in the array, and it's going to pass the returned value for each call into the next call as the first parameter (p). It's useful for accumulating a list as you move across an array.
Because we're looking back at the previous item, we need to make sure we don't go out of bounds on item 0.
Then we're checking to see if this item matches the previous one in the (sorted) list.
Then we're checking (with Array.prototype.some()) whether the value we've found is ALREADY in our list of duplicates...to avoid having duplicate duplicates!
If all of those checks pass, we add the name to our list of duplicate values.

How do I sort one array by the corresponding values in another array?

I have two arrays. The first is for strings and the second is an array for their number of occurrences.
I am trying to get the top 10 most occurrences of words in the first array. I sorted it but somehow I only sort it alphabetically and the second array respectively corresponds to their number of occurrences.
How can I sort the second array from biggest to lowest and, at the same time, sort the first array that match the order of the second?
I'm having trouble inserting my json to my highcharts and I found out why, the numbers should be in square brackets [] I tried already inserting [] in 1 but still does not work please see my post I edit it
this is the data that i should insert in the highchart
[{"name":"#murrayftw","data":[46]},
{"name":"#job","data":[37]},
{"name":"#jobs","data":[25]},
{"name":"#favnashvine","data":[16]},
{"name":"#rollersmusicawards","data":[14]},
{"name":"#soa","data":[13]},
{"name":"#tweetmyjobs","data":[12]},
{"name":"#sman1boyolangu","data":[12]},
{"name":"#supernatural200thepisode","data":[12]},
{"name":"#veteransday","data":[12]}]
Try using a custom compare function with your .sort() call! Check out the documentation here.
I would, in this example (probably not the best way):
Have the unsorted "count" array
Have the unsorted word array
Sort the word array (with a custom function described below)
Sort the count array (no custom function)
The custom compare function would probably be a simple lookup and return the corresponding value in the unsorted count array. (i.e. if the word "a" is 0th index and its relevant count amount is in the 0th index of the count array, return count[0])
If you cannot work with an object try using nested for loops:
var array1 = ['z', 'd', 'e', 'f', 't'], arr1Count = array1.length;
var array2 = [1, 12, 5, 7, 3];
var sortedArray2 = array2.sort(function(x, y) {return y - x});
var i, j, sortedArray1 = [];
for (i = 0; i < arr1Count; i++) {
for (j = 0; j < arr1Count; j++) {
if (array2[j] === sortedArray2[i]) sortedArray1.push(array1[j]); //iterate through the unsorted numeric array (array2) and when it matches the sortedArray2, push this index of array1 into the sortedArray1
}
}
This will create an array of objects that are then sorted by count.
var hashtags = {},
counts = [];
for (var i in data)
{
if(data[i].lang == "en")
{
for (var j in data[i].entities.hashtags)
{
var text = data[i].entities.hashtags[j].text;
if(text) {
if(hashtags[text]) {
hashtags[text].data[0]++;
} else {
hashtags[text] = {
name: text,
data: [1]
};
counts.push(hashtags[text]);
}
}
}
}
}
counts.sort(function(a, b) { return b.data[0] - a.data[0]; });
Simple - don't use 2 arrays but one collection which every element is an object
I took the basics from this post: Sorting JavaScript Object by property value
and completed the demo:
var collection = {car:300, bike:60, motorbike:200, airplane:1000, helicopter:400, rocket:8*60*60}
var sortable = [];
for (var item in collection)
sortable.push([item, collection[item]])
sortable.sort(function(a, b) {return a[1] - b[1]})
collection = {};
for (var i in sortable)
{
collection[sortable[i][0]] = sortable[i][1];
}
console.log(collection);

What kind of array is this in JavaScript?

I have an array that looks like this:
var locationsArray = [['title1','description1','12'],['title2','description2','7'],['title3','description3','57']];
I can't figure out what type of array this is. More importantly, I'm gonna have to create one based on the info there. So, if the number on the end is greater than 10 then create a brand new array in the same exact style, but only with the title and description.
var newArray = [];
// just a guess
if(locationsArray[0,2]>10){
//add to my newArray like this : ['title1','description1'],['title3','description3']
?
}
How can I do it?
Try like below,
var newArray = [];
for (var i = 0; i < locationsArray.length; i++) {
if (parseInt(locationsArray[i][2], 10) > 10) {
newArray.push([locationsArray[i][0], locationsArray[i][1]]);
}
}
DEMO: http://jsfiddle.net/cT6NV/
It's an array of arrays, also known as a 2-dimensional array. Each index contains its own array that has its own set of indexes.
For instance, if I retrieve locationsArray[0] I get ['title1','description1','12']. If I needed to get the title from the first array, I can access it by locationsArray[0][0] to get 'title1'.
Completing your example:
var newArray = [];
// just a guess
if(locationsArray[0][2]>10){
newArray.push( [ locationsArray[0][0], locationsArray[0][1] ] );
}
throw that in a loop and you're good to go.
It's an array of arrays of strings.
Each time there is this : [], it defines an array, and the content can be anything (such as another array, in your case).
So, if we take the following example :
var myArray = ["string", "string2", ["string3-1", "string3-2"]];
The values would be as such :
myArray[0] == "string"
myArray[1] == "string2"
myArray[2][0] == "string3-1"
myArray[2][1] == "string3-2"
There can be as many levels of depth as your RAM can handle.
locationsArray is an array of arrays. The first [] operator indexes into the main array (e.g. locationsArray[0] = ['title1','description1','12']) while a second [] operation indexes into the array that the first index pointed to (e.g. locationsArray[0][1] = 'description1').
Your newArray looks like it needs to be the same thing.
It's an array of array.
var newArray = [];
var locationsArray = [
['title1','description1','12'],
['title2','description2','7'],
['title3','description3','57']
];
for(i = 0; i < locationsArray.length; i++) {
if (locationsArray[i][2] > 10) {
newArray .push([locationsArray[i][0], locationsArray[i][1]]);
}
}
console.log(newArray );

Categories

Resources