Checking length of dictionary object [duplicate] - javascript

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 3 years ago.
I'm trying to check the length here. Tried count. Is there something I'm missing?
var dNames = {};
dNames = GetAllNames();
for (var i = 0, l = dName.length; i < l; i++)
{
alert("Name: " + dName[i].name);
}
dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.

What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);

This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.
I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length is already set.

Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}

Related

In an array, how to make sure the elements don't repeat, in javascript? [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 4 years ago.
I have this code, where the point is to read lottery numbers, and the numbers can not be smaller than 0, nor bigger than 49, nor can they repeat themselves. I don't understand how to put that in the while loop. How can I compare each number is inserted with the numbers previously inserted?
var totoloto=new Array(1);
for(var i=0; i<1; i++) {
totoloto[i]=new Array(5);
for(var j=0; j<5; j++) {
do {
totoloto[i][j] = parseInt(readLine("totoloto="));
} while (totoloto[i][j] < 1 || totoloto[i][j] > 49);
}
print(totoloto[i].toString().replaceAll(",", " "));
}
You can use Set instead of Array and just add values into set. If you don't know, Set contains only unique values.
Another way to do this is just using object:
let obj={}
obj.value1 = true // true is just for example. It doesn't make any sense
obj.value2 = true
// After getting all the keys you can
Object.keys(obj) // it returns all the keys in objecti i.e. your values
So, adding values with the same keys has no effect, because object can have only unique keys.

Javascript Object order incorrect [duplicate]

This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);
As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})
You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

Compare two arrays of "strings" to check if they are equal [duplicate]

This question already has answers here:
Remove items from one array if not in the second array
(5 answers)
Closed 7 years ago.
Good day,
I have two arrays of strings. Strings are just numeric dates (eg: "01/01/2016"...).
I would like to know if there is a good/fast way to compare the two arrays and remove the strings from one array, which are not present in second one.
Example:
First array: ["01/01/2016","02/02/2015", "03/03/2014"]
Second array: ["01/01/2016", "02/02/2015"]
The string "03/03/2014" should be removed from the first array.
I have tried doing it though for() loops of both array lengths, but it seems to be very slow, because the arrays are big (abt. 1000+) indexes in each, like this:
for (var a = 0; a < oilDateArray.length; a++) {
for (var b = 0; b < fuelDateArray.length; b++) {
if (fuelDateArray[b] !== oilDateArray[a]) {
console.log("fuelDateArray not present: " + fuelDateArray[b]);
}
}
}
Is there a specific function/method, which I could use in order to perform the above operation faster?
Thanks in advance and have a nice day!
Try this :
for (var i = 0; i < firstArray.length; i++){
if (secondArray.indexOf(firstArray[i]) == -1){ // indexOf is -1 if not found
firstArray.splice(i, 1); // Remove 1 value at index i
i--; // To re-adjust the index value which is 1 less because of the splice
}
}
It may also be a bit slow, you can try with your array : https://jsfiddle.net/tyrsszaw/4
with jquery
$(array1).filter(array2);
If you have access to Set:
function intersect(arr1, arr2){
var s = new Set(arr1);
return arr2.filter(function(el){
return s.has(el);
});
}
i use jquery for array operations and i'll edit one for your need and paste here, i hope this can help you:
var arr1 = ["01/01/2016","02/02/2015", "03/03/2014"];
var arr2 = ["01/01/2016", "02/02/2015"];
var diff = [];
jQuery.grep(arr2, function(t) {
if (jQuery.inArray(t, arr1) == -1) diff.push(t);
});
alert(diff);​ // what was different will be alerted
i also found this code on stackoverflow sometime ago.
Update: Here is performance related topic you might be interested
Performance of jQuery.grep vs. Array.filter
tldr;
it says grep is about 3 times faster. So stick with my solution. :)

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

How to add undefined element to array?

It's simple, i want to add an undefined element to an array, lets say i have an array Punkt and i have punkt[0] = x: 15, y:"16s" . As i know for ex. the element will have 4 punkt in total i want to add an undefined element to punkt[3], so that also the others punkt[1] and punkt[2] will become undefined.
I need this because somewhere later in my code i do a check for undefined, and throw an error based on this.
Racks is an object that contains an array of objects Punkt
punkt[0] = {
x: 5,
y: "16s" }
What i tried:
racks[trimdevID].punkt[$('#posTable tr:last td:first').text()] = undefined;
You can certainly use the push() routine (see http://www.w3schools.com/jsref/jsref_push.asp). In your example, that would look something like:
// push two undefined elements:
racks[trimdevID].punkt.push(undefined)
racks[trimdevID].punkt.push(undefined)
That assumes that you already have exactly two elements in the array and you want exactly four elements. The more generic version of this is:
var newLength = 4;
for (var idx = racks[trimdevID].punkt.length; idx <= newLength; idx++)
{
racks[trimdevID].punkt.push(undefined);
}
I believe other similar stack questions also have the same answer. You might look at this question for more examples (How to initialize an array's length in javascript?)
undefined is built in property of the global object and it's indeed what you need, so such code for example is working:
var arr = [];
arr.push(undefined);
alert(typeof arr[0]);
This means your problem is elsewhere, from quick look it's because you're using non integer index. Try this instead and it should work:
var index = parseInt($('#posTable tr:last td:first').text(), 10);
if (!isNaN(index))
racks[trimdevID].punkt[index] = undefined;
You can try .push in array
yourArray.push(undefined)
i = 0; //Position Of Undefined
console.log(typeof yourArray[i])

Categories

Resources