Array Length in Javascript - javascript

I am an absolute beginner to programming and Javascript and was watching one of Douglas crockford's videos where he says the following
Arrays unlike objects have a special length member
It is always 1 larger than the highest integer subscript
In this array
var a = [1,2,3,4,5,6,7]
a.length equals to 7.
So I am not quite sure what 1 larger than highest integer subscript means...? Is it just an outdated piece of info from a older version of Javascript or am i missing something ?

length equals to no of elements in the array and index starts from 0 , understand it like you are not starting with 1 instead with 0 so you will have 1 less than total elements(length). so
length = total elements
and
last index = length-1;

It just means that the length of an array is always* its largest index + 1.
Consider:
var a = [];
a[6] = 'foo';
console.log(a.length) //7
a[20] = 'bar';
console.log(a.length) //21
*actually not always, like for example when you use Array constructor with number argument: var a = new Array(5), the array is empty, but it has its length explicitely set to 5

Arrays are indexed from 0 (first element), but length is from 1 (one element) (array won't have length of -1 if there won't be no elements, the length would be 0; if there are 2 elements, second element will have the index of 1 and the length will be 2).

Indexes and lengths are different. While a JavaScript array will start at 0, the length will always be the true number. This is helpful since on a slice, the last number is NOT inclusive.

Related

how to get element that equal or greater than X but smaller than the next X in array?

So i want to get a number that greater than X in array but smaller than Y?
example I have array like this:
["5","10","25",etc]
then the value is 5, so what I want is whenever my value is 5 or greater than 5 but smaller than 10 in array it will only return the 5. like if the value is 6/7/8/9 it will return 5
(Note: The number in array will always different, it's depends on what user set in db)
I have tried with givenNum >= nextNum but it's returning with the number 10 and 25.
any solution?
You could do that :
var array = ["5","10","15","20","25"];
Math.max(...array.filter(nb => nb <= 9))//5
Math.max(...array.filter(nb => nb <= 10))//10
First, you filter the array to keep numbers that are less or equal to the given value.
Then you use Math.max() on the filtered array.
I have tried with givenNum >= nextNum but it's returning with the number 10 and 25.
You are comparing strings instead of numbers, string comparison works alphabetically, since "1" comes before "5" alphabetically, "10" comes before "5" which is why "10" < "5" is true.
You need to convert your strings to numbers using Number() then compare.

How the output has 4 items in the array?

var arr =[1,2,3,4];
var ct = arr.length;
for( var i=0;i<ct;i++){
ct--;
arr[i]+=i;
}
console.log(arr);//1,3,3,4
Explain the code, it's confusing me.
Your loop run 2 times.
First time with i = 0, first item in array increase 0 -> 1
Second time with i= 1, second item in array increase 1 -> 3
The ct decrease so that your loop can not reach third time, array item remain keep old value.
Well, you are not really changing the size of the array.
You create an array with 4 elements (length = 4)
You record the length into an integer, this is a copy of the value
Inside the loop, you decrease the value of ct, which is a copy of the length, so it does not effect the array at all
You increase the current element of the array by what i is at the time, so for the first iteration of the loop, you do 1 + 0
So you see, no changes are made to the length of the array, only the values that the array contains.

Algorithm to find all ways to distribute N objects into M collections

Given a collection with M subcollections, what's a good algorithm (preferably an implementation in Javascript, but any other language or pseudocode would be great as well) to find all possible distributions of N objects into the M subcollections?
For example, given a setup like this:
var collection = [[],[],[]];
var items = ['a','b','c']
I would like the results to look like this
[['a','b','c'],[],[]]
[['a','b'],['c'],[]]
[['a','c'],['b'],[]]
[['a'],['b','c'],[]]
[['b','c'],['a'],[]]
[['b'],['c','a'],[]]
[['c'],['b','a'],[]]
[['a'],['b'],['c']]
[[],['a','b','c'],[]]
[[],['a'],['b','c']]
// etc
N can be larger than, smaller than, or equal to N. Also, in the example, I'm using characters as the items to be distributed, but I'd like the algorithm to be able to distribute objects of any type.
Every object should belong to some collection, so M variants exist for it.
For N objects there are P=M^N variants (N-th power of M).
So we can generate all numbers in range 0..P-1, and consider them as M-base radix numbers.
If k-th digit of number in M-base representation is j, then k-th object belongs to j-th collection.
Example for your case N=3, M=3, P=27
number 12(dec) is equal to 110(three-radix), so collection is
[[a], ['b','c'],[]]
pseudocode
for iii = 0 to Power(M, N) - 1
Clear Collections
i = iii //number of combination
for k = 0 to N - 1 do
j = i mod M //integer modulo, %
//gives k-th digit of number i in M-radix representation
//counting from right to left
Collections[j].Add(Object[k])
i = i div M //integer division
output Collections

Puzzling javascript behavior

I typed the following into the chrome console:
> Array.prototype.slice.call([1,2], 0)
[1, 2]
> Array.prototype.slice.call([1,2], 1)
[2]
Why does the first call not return 1?
Array.prototype.slice.call([1,2], 0) returns all elements of the array starting from index 0, and puts the whole into the array.
Array.prototype.slice.call([1,2], 1) returns all elements of the array starting from index 1, and puts the whole into the array, however this time it finds only 1 element, the 2.
Slice with one argument returns the array from the index position you give in the argument. In your case 0 marks the index position 0, so it returns the whole array.
Array.prototype.slice.call([1,2,3,4,5], 0)
//=> [1,2,3,4,5] because index to start is 0
Array.prototype.slice.call([1,2,3,4,5], 2)
//=> [3,4,5] because index to start is 2
The second argument would be how many element it slices out starting from index, so:
Array.prototype.slice.call([1,2,3,4,5], 0, 1)
//=> [1] because index to start is 0 and number of elements to slice is 1
Array.prototype.slice.call([1,2,3,4,5], 2, 2)
//=> [3,4] because index to start is 2 and number of elements to slice is 2
Find more in the documentation here
As indicated here, the slice method accepts a start and optionally an end offset, not the index of the element to slice out. If no offset is provided, it will slice to the end of the array.
In your first example, slice starts from element 0, while in the second example it starts from element 1. In both occassions it will any elements it can find at that index and after, since you have not specified an offset.
First parameter to slice is the start index in the array (counting from zero).
The second parameter (which is not given in either of your examples), is the end. Precisely it is: one past the inclusive end index. Anyway, it defaults to the end of the array, which is the behaviour you see.
Array.prototype.slice.call([1,2], 0, 1)
should give you [1]
slice.call(arguments, Fromindex);
The Fromindex means to slice the arguments list from index to the end.
as your case
slice the arguments from index 1
thats why you get [2]

Javascript: explain this one line of code to me please

I have this simple array:
var RedirUrl = new Array(4);
RedirUrl[0] = 'http://mafi.se/mf_redir/new_install_'+this_version+'.html';
RedirUrl[1] = 'http://ifurls.com/mf_redir/new_install_'+this_version+'.html';
RedirUrl[2] = 'http://ez.se/xml-update/mf_redir/new_install_'+this_version+'.html';
RedirUrl[3] = 'http://ilovre.net/mf_redir/new_install_'+this_version+'.html';
RedirUrl[4] = 'http://rihel.com/mf_redir/new_install_'+this_version+'.html';
and then
RedirUrl.sort(function() {return 0.5 - Math.random()})
The last bit is what is confusing me.
I understand the "sort" and I understand the Math.random but the return 0.5 confuses me... what exactly is that?
(Needless to say I downloaded it off the net as it does what i want it to do... but i just dont understand it.)
It's sorting the list of URLs with a sorting method that randomly returns values that are greater than or less than 0 in about half the cases each.
Math.random() returns a number betweeen 0 and 1. Therefore 0.5 - Math.random() is a randomly decided value between -0.5 and 0.5. About half of those values are greater than zero and half of those are less than zero.
So about half of the time the comparison function will say that the first object is greater than the second and half of the time it will say the opposite.
It's a simple way to randomly shuffle the array. As has been pointed out in the comments, it's not a good way to shuffle an array (because the distribution is not even).
This question has a working implementation of the known-good Fisher-Yates shuffle.
sort() takes a function for comparing values in an array as it's argument. Here the sort() method is told to give a random number between 0.0 and 1.0, and the 0.5 is there to make the random number go between -0.5 to 0.5, this randomly saying lesser or greater than.
A comparator function should return < 0 to indicate that the first value is smaller, > 0 to indicate that it's larger, and 0 to indicate equality. Math.random() returns a number between 0 and 1. So, by doing the subtraction, you get random ordering!
This would shuffle the array. If a function is used withing Array.sort() then it usually has two parameters which are compared Array.sort(function(a,b){}). A return value less than 0 indicates that a is before b, greater than 0 that a is after b and 0 that they have the same order. Using 0.5 - Math.random() means that you should get values greater or less than 0 at random.
Seems the script will randomly shuffle this array by having the compare function randomly returns a value between -0.5 and +0.5
Also it generates an array of length 4 but then fills it with 5 items
I suggest this format instead
var RedirUrl = [
'http://mafi.se/mf_redir/new_install_'+this_version+'.html',
'http://ifurls.com/mf_redir/new_install_'+this_version+'.html',
'http://ez.se/xml-update/mf_redir/new_install_'+this_version+'.html',
'http://ilovre.net/mf_redir/new_install_'+this_version+'.html',
'http://rihel.com/mf_redir/new_install_'+this_version+'.html'
]
Here sort will be performing a sort based on the comparison function that you pass to it.
In your case, it is:
function() {return 0.5 - Math.random()}
Assuming you are familiar with comparison based sorting, the function should return a negative value indicating that the left hand side value is less, zero if they are equal and positive if left hand side value is greater than the right hand side value, much like C function strcmp().
Looking into the function that you have, it will try to perform a random sort, that is try to shuffle the array.
On an additional note, this kind of shuffling algorithm is not an ideal one. It will be self contradictory. Since everything will occur at random, it may lead to situations where say, a.

Categories