init Array with 5 zero elements [duplicate] - javascript

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;
}

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) ;`

What is the purpose of the new Array(9) syntax?

I can't use .map on an array created by the Array-constructor with a set length:
// create an array with 9 empty elements
let array = new Array(9);
// assign an array to each of the array's elements
array = array.map(() => new Array(1, 2, 3));
console.log(array);
One way to achieve the desired effect by using a for loop:
// create an array with 9 empty elements
let array = new Array();
// assign an array to each of them
for(let i = 0; i < 9; i++){
array.push(new Array(1, 2, 3));
}
console.log(array)
Why can't .map be used on an array with empty placeholders? What is the purpose of the Array(3) - syntax?
You can use new Array(n) to create a sparse array, an array with gaps, with the length of n. According to MDN article about Array#map:
Due to the algorithm defined in the specification if the array which
map was called upon is sparse, resulting array will also be sparse
keeping same indices blank.
To solve that, you can use Array#fill, to fill the sparse array with a value (even undefined will do), and then you can map it with whatever you want.
// create an array with 9 empty elements
const array = new Array(9);
// assign an array to each of the array's elements
const result = array
.fill()
.map(() => [1, 2, 3]);
console.log(result);

how can i have the first 3 elements of an array of variable length in Javascript [duplicate]

This question already has answers here:
How to get first N number of elements from an array
(14 answers)
Closed 5 years ago.
i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.
here's what i've done :
var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)
my "solution" work only for an array of 4 element ( -1 )
Is there a better way to use the splice method ?
Thanks for your help
You could use Array#slice for the first three items.
return this.users.sort(this.triDec).slice(0, 3);
Don't you want to use a const value for diffSplice like
var diffSplice = 3;
return this.users.sort(this.triDec).slice(0,diffSplice)
try running
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));
refer to Array Silce
Fill out the deletecount for Splice:
var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);
check MDN

forEach on a 'new Array' isn't doing what I expect

I'm just learning how to use JS higher-order functions (map, forEach, reduce, etc), and have stumbled into confusion. I'm trying to write a simple 'range' function, but can't seem to populate my output array. This is the goal:
range(1, 4) // [1, 2, 3, 4]
I'm getting this:
[undefined × 4]
Here is my code:
function range(num1, num2) {
var rangeArr = new Array((num2 + 1) - num1);
return rangeArr.map(function(e, i, arr) {return arr[i] = num1 + i});
}
What am I missing here? As far as I can tell the problem appears to have something to do with the way I'm utilizing 'new Array', but beyond that I'm lost.
Oh, and here's the part that really confuses me. This works fine:
function bleck() {
var blah = [1, 2, 3, 4];
var x = 'wtf';
return blah.map(function(e, i, arr) {return arr[i] = x})
}
["wtf", "wtf", "wtf", "wtf"]
Thanks!!
The forEach method iterates over the indices of the array. Interestingly enough, when you create a new array via new Array(n), it contains no indices at all. Instead, it just sets its .length property.
> var a = new Array(3);
> console.info(a)
[]
> console.info([undefined, undefined, undefined])
[undefined, undefined, undefined]
MDN describes forEach, and specifically states:
forEach executes the provided callback once for each element of the
array with an assigned value. It is not invoked for indexes which have
been deleted or elided.
Here's a neat technique to get an array with empty, but existing, indices.
var a = Array.apply(null, Array(3));
This works because .apply "expands" the elided elements into proper arguments, and the results ends up being something like Array(undefined, undefined, undefined).
The array is defined with 4 entires each of which is undefined.
Map will not iterate over undefined entires, it skips them.
callback is invoked only for indexes of the array which have assigned
values; it is not invoked for indexes that are undefined, those which
have been deleted or which have never been assigned values.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
When you create a new Array(x) it is creating what is called a sparse array, which might behave a bit differently, as you can see, some browsers will say [undefined x 20,"foo", undefined x 5] if you just set one value, and I believe it doesn't iterate over those values.
The problem is that map doesn't iterate undefined entries (*).
I suggest using a for loop instead:
var rangeArr = new Array((num2 + 1) - num1);
for(var i=0; i<=num2-num1; ++i)
rangeArr[i] = num1 + i;
return rangeArr;
(*) With undefined entries I mean rangeArr.hasOwnProperty(i) === false, not to be confused with rangeArr[i] === void 0.

Array.size() vs Array.length

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) ;`

Categories