Array.size() vs Array.length - javascript

What is the difference between the two?
So I know that array.size() is a function while array.length is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?
var x = [];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
x =[1,2,3];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
Will print:
0, 0, true
3, 3, true

Array.size() is not a valid method
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).

.size() is not a native JS function of Array (at least not in any browser that I know of).
.length should be used.
If
.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.
or
There might be some plugin on your browser that is mucking with the Array prototype.

The .size() function is available in Jquery and many other libraries.
The .length property works only when the index is an integer.
The length property will work with this type of array:
var nums = new Array();
nums[0] = 1;
nums[1] = 2;
print(nums.length); // displays 2
The length property won't work with this type of array:
var pbook = new Array();
pbook["David"] = 1;
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0
So in your case you should be using the .length property.

.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.
If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.

array.length isn't necessarily the number of items in the array:
var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101
The length of the array is one more than the highest index.
As stated before Array.size() is not a valid method.
More information

The property 'length' returns the (last_key + 1) for arrays with numeric keys:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
log.info( nums.length );
will print 12!
This will work:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
nums [ 12 ] = 12 ;
log.info( nums.length + ' / '+ Object.keys(nums).length );

The .size() method is deprecated as of jQuery 1.8. Use the .length property instead
See: https://api.jquery.com/size/

Size detects duplicates, it will return the number of unique values
const set1 = new Set([1, 2, 3, 4, 5, 5, 5, 6]);
console.log(set1.size);
// expected output: 6

Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.
The size accessor property returns the number of (unique) elements in a Set object.
const set1 = new Set();
const object1 = new Object();
set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);
console.log(set1.size);
// expected output: 3
And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4

we can you use .length property to set or returns number of elements in an array. return value is a number
> set the length: let count = myArray.length;
> return lengthof an array : myArray.length
we can you .size in case we need to filter duplicate values and get the count of elements in a set.
const set = new set([1,1,2,1]);
console.log(set.size) ;`

Related

Counting variables in for loops [duplicate]

What is the difference between the two?
So I know that array.size() is a function while array.length is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?
var x = [];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
x =[1,2,3];
console.log(x.size());
console.log(x.length);
console.log(x.size()==x.length);
Will print:
0, 0, true
3, 3, true
Array.size() is not a valid method
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
.size() is not a native JS function of Array (at least not in any browser that I know of).
.length should be used.
If
.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.
or
There might be some plugin on your browser that is mucking with the Array prototype.
The .size() function is available in Jquery and many other libraries.
The .length property works only when the index is an integer.
The length property will work with this type of array:
var nums = new Array();
nums[0] = 1;
nums[1] = 2;
print(nums.length); // displays 2
The length property won't work with this type of array:
var pbook = new Array();
pbook["David"] = 1;
pbook["Jennifer"] = 2;
print(pbook.length); // displays 0
So in your case you should be using the .length property.
.size() is jQuery's, much probably you're either confusing with or took from someone else who had imported the jQuery library to his project.
If you'd have jQuery imported and you'd write like $(array).size(), it would return the array length.
array.length isn't necessarily the number of items in the array:
var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101
The length of the array is one more than the highest index.
As stated before Array.size() is not a valid method.
More information
The property 'length' returns the (last_key + 1) for arrays with numeric keys:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
log.info( nums.length );
will print 12!
This will work:
var nums = new Array();
nums [ 10 ] = 10 ;
nums [ 11 ] = 11 ;
nums [ 12 ] = 12 ;
log.info( nums.length + ' / '+ Object.keys(nums).length );
The .size() method is deprecated as of jQuery 1.8. Use the .length property instead
See: https://api.jquery.com/size/
Size detects duplicates, it will return the number of unique values
const set1 = new Set([1, 2, 3, 4, 5, 5, 5, 6]);
console.log(set1.size);
// expected output: 6
Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.
The size accessor property returns the number of (unique) elements in a Set object.
const set1 = new Set();
const object1 = new Object();
set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);
console.log(set1.size);
// expected output: 3
And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// expected output: 4
we can you use .length property to set or returns number of elements in an array. return value is a number
> set the length: let count = myArray.length;
> return lengthof an array : myArray.length
we can you .size in case we need to filter duplicate values and get the count of elements in a set.
const set = new set([1,1,2,1]);
console.log(set.size) ;`

Rotate multiple banner images [duplicate]

By default the indexing of every JavaScript array starts from 0. I want to create an array whose indexing starts from 1 instead.
I know, must be very trivial... Thanks for your help.
It isn't trivial. It's impossible. The best you could do is create an object using numeric properties starting at 1 but that's not the same thing.
Why exactly do you want it to start at 1? Either:
Start at 0 and adjust your indices as necessary; or
Start at 0 and just ignore index 0 (ie only use indices 1 and up).
A simple solution is to fill the zeroth item:
var map = [null, 'January', 'February', 'March'];
'First month : ' + map[1];
Semantically it would be better to use an object:
var map = {1:'January', 2:'February', 3:'March'};
'First month : ' + map[1];
Note these keys are not ints actually, object keys are always strings.
Also, we can't use dot notation for accessing. (MDN - Property Accessors)
I'd choose the first solution, which I think is less confusing.
Since this question also pops up for a Google search like "javascript start array at 1" I will give a different answer:
Arrays can be sliced. So you can get a sliced version of the Array like this:
var someArray = [0, 1, 2, 3];
someArray.slice(1);
[1, 2, 3]
someArray.slice(2, 4);
[2, 3]
Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
You could use delete to remove the first element like so:
let arr = ['a','b','c'];
delete arr[0];
console.log(arr[0]);
console.log(arr[1]);
Or just not define it at all:
let arr = [,'b','c'];
console.log(arr[0]);
console.log(arr[1]);
If you want to make sure that you always get the first truthy element regardless of the index and have access to ES6 you can use:
arr.find(Boolean)
The question asks "How to create an array in JavaScript whose indexing starts at 1". The accepted answer states "It isn't trivial. It's impossible."
This is true, and should be understood for good reason. However, you can create an array and omit setting the first element, in which case it will still exist (hence the accepted answer being correct) but it'll be marked as empty for you.
let usernames = ['bob', 'sally', 'frank']
let myArray = [];
let arrayIndex = 1;
usernames.map(username => {
myArray[arrayIndex] = username;
arrayIndex++;
})
console.log(myArray);
Array(4) [ <1 empty slot>, "bob", "sally", "frank" ]
1: "bob"
2: "sally"
3: "frank"
​length: 4
Notice that the length is "4".
console.log(myArray[0]);
undefined
Using this, there's a quirk in our favour whereby using Object.keys() on an array doesn't return empty (undefined) elements. So with the above array:
console.log(Object.keys(myArray).length);
3
Note: This is arguably a little hacky so use it with caution.
As zero of something rarely exists in our world, doing this might be useful where you are only going to access pre-defined indexes. An example would be if you have pages of a book. There isn't a page 0 as that makes no sense. And if you are always access a value directly, e.g.
const currentPage = pages[1];
Then this is fine in my opinion, as long as the code shows intent. Some will argue that ignoring a valid array index is futile, and I don't fully disagree. However, it's also futile and very annoying when I want to get page 35 of a book and the array index is 34. Meh!
When you loop your (dodgy) array with map it ignores the 0 index you didn't want:
myArray.map((value, index) => {
console.log(index);
console.log(value);
})
1
bob
2
sally
3
frank
For general use however, you should use index 0, so when you loop some data and spit things out you're not going to get caught out by the first one being empty.
Okay, according to #cletus you couldn't do that because it's a built-in javascript feature but you could go slightly different way if you still want that. You could write your own index-dependent functions of Array (like reduce, map, forEach) to start with 1. It's not a difficult task but still ask yourself: why do I need that?
Array.prototype.mapWithIndexOne = function(func) {
const initial = []
for (let i = 1; i < this.length + 1; i++) {
initial.push(func(this[i - 1], i))
}
return initial
}
const array = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
console.log(array.mapWithIndexOne((element, index) => `${element}-${index}`))
// => ["First-1", "Second-2", "Third-3", "Fourth-4", "Fifth-5"]
Codepen: https://codepen.io/anon/pen/rvbNZR?editors=0012
Using Array.map
[,1,2,3].map((v, i) => ++i)
Just wanted to point out that an index in c ish languages is also the offset from the first element. This allows all sorts of offset math where you don't have to subtract 1 before doing the math, only to add the 1 back later.
if you want a "1" array because the indexes are mapped to other values, that's the case for an enumeration or a hash.
First add this function to your javascript codes:
var oneArray = function(theArray)
{
theArray.splice(0,0,null);
return theArray
}
Now use it like this:
var myArray= oneArray(['My', 'name', 'is', 'Ram']);
alert(myArray[1]); << this line show you: My
See live demo
Just prepend a null:
a = [1, 2, 3, 4]
a.unshift(null)
a[3] // 3
Simple, just make two changes to the classic Javascript for loop.
var Array = ['a', 'b', 'c'];
for (var i = 1; i <= Array.length; i++) {
//"i" starts at 1 and ends
//after it equals "length"
console.log(i);
}

init Array with 5 zero elements [duplicate]

This question already has answers here:
Most efficient way to create a zero filled JavaScript array?
(45 answers)
Closed 4 years ago.
Hello I want to init Array with 5 zero elements in JS. Without classic initiation var arr = [0, 0, 0, 0, 0]
I try some variant:
var arr = new Array(5).map(() => 0);
var arr = new Array(5).map(function () {return 0;});
var arr = Array(5).map(function () {return 0;});
but this examples are not working.
Either use .fill:
const arr = new Array(5).fill(0);
console.log(arr);
or Array.from, which has a built-in map function you can pass as a second parameter:
const arr = Array.from({ length: 5 }, () => 0);
console.log(arr);
See MDN:
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
Using Array.from as above assigns undefined values to each element of the array, whereas new Array does not, which is why you can map after Array.from but not after invoking the Array constructor.
You need use method fill for array's in initialization.
example:
var arr = new Array(5).fill(0);
May a for loop help you?
For(i=0; i<N; i++){
array[i]=value;
}
For a 5 length array of 0 it becomes
for(i=0; i<5; i++){
array[i]=0;
}

javascript - map one array to a second array with a negative index offset

Alright, I'm taking an array, and making another array from it with the only difference being the indexes are displaced by an arbitrary number determined using two reference points (one in each array). Doing this creates negative indexes, which if it didn't stop the script from working, would be useful. Is there any way to have the second array have the negative indexes and work, or am I going to have to use an all-together different method? I rewrote the code to be a simple case.
var firstArray = {
field: [ 1, 2, 3, 4, 5],
referenceIndex : 2
};
var secondArray = {
referenceIndex: 1,
offset: 0,
field : {}
};
// Create secondArray.field by finding the offset.
secondArray.offset = firstArray.referenceIndex - secondArray.referenceIndex;
for (i=0; i < firstArray.field.length; i++){
alert([i - secondArray.offset, firstArray.field[i]].join(" "));
secondArray.field[i - secondArray.offset] = firstArray.field[i]; //creates a negative index.
}
An array can have (in a strict sense) only positive integer as indices. However it is also an object, so it can take any string as a property. So in a sense, it will 'work', but do not trust Array#length to have the right value.
var arr = [1,2,3];
arr.length //3
arr[10] = 10;
arr.length //11
arr["blah"] = 100;
arr.length //still 11
arr[-1] = 200;
arr.length //still 11
I'd also like to point you to this excellent article - http://javascriptweblog.wordpress.com/2010/07/12/understanding-javascript-arrays/
No you can't have negative indices and have it work properly, however, you possibly could save a number and add it to your index to create a positive value. For example you have indeces -2 through 4. In the array this would be 0 - 6 so you would need to add or subtract 2 to get to the value of the index you want.

How to create an array in JavaScript whose indexing starts at 1?

By default the indexing of every JavaScript array starts from 0. I want to create an array whose indexing starts from 1 instead.
I know, must be very trivial... Thanks for your help.
It isn't trivial. It's impossible. The best you could do is create an object using numeric properties starting at 1 but that's not the same thing.
Why exactly do you want it to start at 1? Either:
Start at 0 and adjust your indices as necessary; or
Start at 0 and just ignore index 0 (ie only use indices 1 and up).
A simple solution is to fill the zeroth item:
var map = [null, 'January', 'February', 'March'];
'First month : ' + map[1];
Semantically it would be better to use an object:
var map = {1:'January', 2:'February', 3:'March'};
'First month : ' + map[1];
Note these keys are not ints actually, object keys are always strings.
Also, we can't use dot notation for accessing. (MDN - Property Accessors)
I'd choose the first solution, which I think is less confusing.
Since this question also pops up for a Google search like "javascript start array at 1" I will give a different answer:
Arrays can be sliced. So you can get a sliced version of the Array like this:
var someArray = [0, 1, 2, 3];
someArray.slice(1);
[1, 2, 3]
someArray.slice(2, 4);
[2, 3]
Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
You could use delete to remove the first element like so:
let arr = ['a','b','c'];
delete arr[0];
console.log(arr[0]);
console.log(arr[1]);
Or just not define it at all:
let arr = [,'b','c'];
console.log(arr[0]);
console.log(arr[1]);
If you want to make sure that you always get the first truthy element regardless of the index and have access to ES6 you can use:
arr.find(Boolean)
The question asks "How to create an array in JavaScript whose indexing starts at 1". The accepted answer states "It isn't trivial. It's impossible."
This is true, and should be understood for good reason. However, you can create an array and omit setting the first element, in which case it will still exist (hence the accepted answer being correct) but it'll be marked as empty for you.
let usernames = ['bob', 'sally', 'frank']
let myArray = [];
let arrayIndex = 1;
usernames.map(username => {
myArray[arrayIndex] = username;
arrayIndex++;
})
console.log(myArray);
Array(4) [ <1 empty slot>, "bob", "sally", "frank" ]
1: "bob"
2: "sally"
3: "frank"
​length: 4
Notice that the length is "4".
console.log(myArray[0]);
undefined
Using this, there's a quirk in our favour whereby using Object.keys() on an array doesn't return empty (undefined) elements. So with the above array:
console.log(Object.keys(myArray).length);
3
Note: This is arguably a little hacky so use it with caution.
As zero of something rarely exists in our world, doing this might be useful where you are only going to access pre-defined indexes. An example would be if you have pages of a book. There isn't a page 0 as that makes no sense. And if you are always access a value directly, e.g.
const currentPage = pages[1];
Then this is fine in my opinion, as long as the code shows intent. Some will argue that ignoring a valid array index is futile, and I don't fully disagree. However, it's also futile and very annoying when I want to get page 35 of a book and the array index is 34. Meh!
When you loop your (dodgy) array with map it ignores the 0 index you didn't want:
myArray.map((value, index) => {
console.log(index);
console.log(value);
})
1
bob
2
sally
3
frank
For general use however, you should use index 0, so when you loop some data and spit things out you're not going to get caught out by the first one being empty.
Okay, according to #cletus you couldn't do that because it's a built-in javascript feature but you could go slightly different way if you still want that. You could write your own index-dependent functions of Array (like reduce, map, forEach) to start with 1. It's not a difficult task but still ask yourself: why do I need that?
Array.prototype.mapWithIndexOne = function(func) {
const initial = []
for (let i = 1; i < this.length + 1; i++) {
initial.push(func(this[i - 1], i))
}
return initial
}
const array = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
console.log(array.mapWithIndexOne((element, index) => `${element}-${index}`))
// => ["First-1", "Second-2", "Third-3", "Fourth-4", "Fifth-5"]
Codepen: https://codepen.io/anon/pen/rvbNZR?editors=0012
Using Array.map
[,1,2,3].map((v, i) => ++i)
Just wanted to point out that an index in c ish languages is also the offset from the first element. This allows all sorts of offset math where you don't have to subtract 1 before doing the math, only to add the 1 back later.
if you want a "1" array because the indexes are mapped to other values, that's the case for an enumeration or a hash.
First add this function to your javascript codes:
var oneArray = function(theArray)
{
theArray.splice(0,0,null);
return theArray
}
Now use it like this:
var myArray= oneArray(['My', 'name', 'is', 'Ram']);
alert(myArray[1]); << this line show you: My
See live demo
Just prepend a null:
a = [1, 2, 3, 4]
a.unshift(null)
a[3] // 3
Simple, just make two changes to the classic Javascript for loop.
var Array = ['a', 'b', 'c'];
for (var i = 1; i <= Array.length; i++) {
//"i" starts at 1 and ends
//after it equals "length"
console.log(i);
}

Categories