Javascript, Getting Length of String Held in Array - javascript

k = [['a'], ['ab'], ['abc']];
alert(k[2].length);
The above code fragment returns 1.
How can I get the length of the string, 3 in this case?

The object is not what is expected. Consider:
k = [['a'], ['ab'], ['abc']];
a = k[2] // -> ['abc']
a.length // -> 1 (length of array)
b = k[2][0] // -> 'abc'
b.length // -> 3 (length of string)

In your example, k is not a normal array containing strings. It contains sub-arrays, which contain the strings. You should declare k this way:
k = ['a', 'ab', 'abc'];
If you do want to use your own declaration, you could do this:
alert(k[2][0].length);​

Related

How to loop/process Javascript Key:Value pairs?

Consider the following code:
a = {};
a['a'] = 1;
a['b'] = 3;
a['c'] = 5;
a['d'] = 2;
b = [];
b['a'] = 1;
b['b'] = 3;
b['c'] = 5;
b['d'] = 2;
console.log(typeof a, typeof b);
console.log(a);
console.log(b);
And the output console.log is as follow:
object object
{ a: 1, b: 3, c: 5, d: 2 }
[ a: 1, b: 3, c: 5, d: 2 ]
Granted that they are of both type object, to my understanding, a is an object of key:value pairs, where as b is an array of [key:value] pairs. Is that the right assumption?
And aside from a for(index in array) pattern of looping, where I have to use the iterator index to grab the value (array[index]), is there a better, more simple method of looping through these key/value pairs to grab the index/value or to just process the data at each index, sort of like map or reduce for arrays?
One such problem I ran into was, if I wanted to grab the key with the least count (in the above examples, it would be 'a'), is there a way to do it without using the for( index in array) pattern?
In Javascript arrays are objects, so you can add keys like you are doing in your example above, but this is not the normal way to use arrays and will probably confuse a lot of people looking at your code. There are occasional when it's useful to add a property to an array, but using them just as key stores definitely not the norm.
If you want an ordered collections with numeric indexes, use an array:
let arr = []
arr.push(10)
arr.push(20)
console.log(arr)
console.log(arr[0])
If you want properties where order isn't important and you will have string keys, use an object. In the above example you are using both types like objects — there's no reason to use an array like that.
Having said that if you want an iterator of values from an object, you can use Object.values(). This delivers an array of values from an object if you only want to process the values:
a = {};
a['a'] = 1;
a['b'] = 3;
a['c'] = 5;
a['d'] = 2;
console.log(Object.values(a))
// process them
let newArr = Object.values(a).map(n => n * 10)
console.log(newArr)
Object.entries is also useful — it returns an array of key/value pairs, which, with reduce() makes a nice way to find the minimum:
a = {
a: 1,
b: 3,
c: 5,
d: 2
};
// current will be an array of the form [key, value]
let [minKey, minValue] = Object.entries(a).reduce((min, current) => min[1] < current[1] ? min : current)
console.log(minKey, minValue)

What is happening when adding a number to the array element

Example 1:
Var arr = [1,2,3] + 1;
console.log(arr) // "1,2,31"
typeof arr // String
Example 2:
var arr = 5 + ["h","e","l","l","o"];
console.log(arr) // "5h,e,l,l,o";
typeof arr // String
Doing the above concatenate the number/string to the last/first element in the array. Would like to understand what happens here?
While you are using + (concatenation in this case ), it's applying toString() method to the array. So it's just concatenating with the result and not appending with last or first element.
The Array object overrides the toString method of Object. For Array objects, the toString method joins the array and returns one string containing each array element separated by commas.
JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation. (Taken from here)
Check the following snippet all those are results the same.
var arr = [1, 2, 3];
// all these are providing the same result
// result of toString method
console.log(arr.toString())
// concatenation with empty string at end
console.log(arr + "")
// concatenation with empty string at start
console.log("" + arr);
To add an element to the array use one of this methods.
As #Pranav C Balan mentioned + operator try to concatenate 2 values. That's one of the most weird parts in Javascript. Here is a very helpful page with all of subtleties JS Garden
Example 1:
Var arr = [1,2,3];
arr.push(1)
console.log(arr) // [1,2,3,1]
typeof arr // object
Example 2:
var arr = ["h","e","l","l","o"];
arr.unshift(5);
console.log(arr) // [5,"h","e","l","l","o"];
typeof arr // object

for( in ) loop index is string instead of integer [duplicate]

This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
Consider following code:
var arr = [111, 222, 333];
for(var i in arr) {
if(i === 1) {
// Never executed
}
}
It will fail, because typeof i === 'string'.
Is there way around this? I could explicitly convert i to integer, but doing so seems to defeat the purpose using simpler for in instead of regular for-loop.
Edit:
I am aware of using == in comparison, but that is not an option.
You have got several options
Make conversion to a Number:
parseInt(i) === 1
~~i === 1
+i === 1
Don't compare a type (Use == instead of ===):
i == 1 // Just don't forget to add a comment there
Change the for loop to (I would do this but it depends on what you are trying to achieve):
for (var i = 0; i < arr.length; i++) {
if (i === 1) { }
}
// or
arr.forEach(function(item, i) {
if (i === 1) { }
}
By the way you should not use for...in to iterate through an array. See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for..in should not be used to iterate over an Array where index order
is important. Array indexes are just enumerable properties with
integer names and are otherwise identical to general Object
properties. There is no guarantee that for...in will return the
indexes in any particular order and it will return all enumerable
properties, including those with non–integer names and those that are
inherited.
Because the order of iteration is implementation dependent, iterating
over an array may not visit elements in a consistent order. Therefore
it is better to use a for loop with a numeric index (or Array.forEach
or the non-standard for...of loop) when iterating over arrays where
the order of access is important.
With === you compare also the type of values. Use == instead:
if ( i == 1 ) {}
or cast i to integer:
if ( +i === 1 ) {}
Also you can try with 'standard' for loop:
for (var i = 0; i < arr.length; i++) {
if (i === 1) {}
}
If you don't need browser support below IE9, you can use Array.forEach
If you do, use the good ol' for (i = 0; i < arr.length; i++) {} loop.
Is this what you mean?
var arr = [1, 2, 3];
for(var i in arr) { //i is not the value of an element of the array, but its "attribute name"
if(arr[i] === 1) {
}
}
In any case, I'd use the good old classic for syntax, it's the recommended way to deal with arrays
for-in loops properties in object, you could use for-of to loop array.
for (const i in [11, 22, 33, 44, 55]) {
console.log(`${typeof i}: ${i}`);
}
string: 0
string: 1
string: 2
string: 3
string: 4
const obj = {
11: 'a',
22: 'b',
33: 'c',
44: 'd',
55: 'e',
}
for (const i in obj) {
console.log(`${typeof i}: ${i} -> ${obj[i]}`);
}
string: 11 -> a
string: 22 -> b
string: 33 -> c
string: 44 -> d
string: 55 -> e
for (const i of [11, 22, 33, 44, 55]) {
console.log(`${typeof i}: ${i}`);
}
number: 11
number: 22
number: 33
number: 44
number: 55

Array of length bracket notation

If I want to make an array that is say of length 3 using bracket notation, should I just write: var foo = [,,];
I was more used to writing: var foo = new Array(3);
I noticed that if I removed one , that my code still worked which is surprising because I am accessing all 3 elements after assigning them. How is it that it would still work?
if u do
a = []
a[3] = 100
the indices 0,1,2 will be filled in with undefined for u. u do not have to set a specific array length before using certain indices. array will grow as u use it.
all these are the same:
a = [,,,]
b = []
b.length = 3
c = new Array(3)
d = []
d[2] = undefined

unable to get array length of object property in javascript

defined a simple javascript object and assigned array to one property but not able to get the length of the array. returning 2 rather than 1 for below code.
//activity object
var activity={
timer:0,
questions_completed:new Array(2),
knifes:0,
getTimer:function(){
return timer;
}
};
alert(activity.questions_completed.length); //getting 2?
new Array with a single parameters passed to it as number, will create an array with specific length:
var arr = new Array(2);
arr;
// -> [undefined, undefined]
arr.length;
// -> 2
Instead use [] notation:
var arr = [2];
arr;
// -> [2]
arr.length;
// -> 1
var activity = {
timer:0,
questions_completed: [2],
knifes:0,
getTimer:function(){
return timer;
}
};
alert(activity.questions_completed.length);
// 1
The below line defines the length of your array which is 2, however you have not pushed any item in your array the length will show 2, which is absolutely correct..!
questions_completed:new Array(2)

Categories

Resources