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

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

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

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

Copy an array into the middle of a larger array in Javascript

I've searched through the answers here, but I can only find this question answered for other languages.
So I have 2 Uint8 typed arrays.
var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];
I want to replace the contents of arr2 with arr1 starting at the 4th position. So that arr2 will be:
arr2 = [0,1,2,0,0,0,6,7,8,9];
If I wasn't trying to do this in the middle of the array I could use set like this:
arr2.set(arr1);
And I would get:
arr2 = [0,0,0,4,5,6,7,8,9];
I know I can loop through the arr2 and individually copy the values, but performance wise this is very slow compared to set (and performance matters to me because it's copying an entire array of canvas img data 24 times a second).
Is there any function that can copy into the middle of an array, but with the performance of set?
Use the typedarray.set(array[, offset]) offset.
offset Optional
The offset into the target array at which to begin
writing values from the source array. If you omit this value, 0 is
assumed (that is, the source array will overwrite values in the target
array starting at index 0).
const arr1 = new Uint8Array([0,0,0]);
const arr2 = new Uint8Array([0,1,2,3,4,5,6,7,8,9]);
arr2.set(arr1, 4);
console.log(arr2);
You can use the slice method with the spread syntax:
const shim = (source, index, target) => [
...source.slice(0, index),
...target,
...source.slice(index)
]
var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];
const newArr = shim(arr2, 3, arr1);
console.log(newArr);
.slice will not mutate the array and will return a new shallow copy of it (unlike splice).
Since you are using typed array. Don't you can use the offset of the set method?
arr2.set(arr1, 3)
To overwrite from the 4th element of the target array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set
To me it does just what you need, if I understand your question.

Adding array of arrays dynamically in javascript

I am trying to add array of arrays dynamically in javascript. I need the data in the following format -
var dataArray = [[],[],[],.....,[]];
How can I initialize this kind of array? Suppose if I have three arrays to be added, I can initialize as follows -
var dataArray = [[],[],[]];
This will accept only three records to be added. But, what should I do in case of adding large number of arrays? Here I cannot know the amount of data I get as input.
I have tried using concat() and merge() methods, these are adding contents directly in to a single array, but that is not what I wanted.
Can any one please help me out on this?
You can build or add an array into an array like this:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
Or, if you want to add elements to the sub-arrays:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
dataArray[0].push(4);
dataArray[1].push(9);
console.log(dataArray); // [[1,2,3,4], [3,4,5,9]]
You initialize a sub-array by assigning an array to the element of the outer array. You can then use array operations directly on the sub-array element:
// create a sub-array element
dataArray[2] = [];
dataArray[2].push(8);
dataArray[2].push(7);
console.log(dataArray[2]); // [8,7]
console.log(dataArray); // [[1,2,3,4], [3,4,5,9], [8,7]]
The key thing it appears you don't understand is that an array of arrays is just that. It's an outer array where each element in the outer array is itself an array. You use ordinary array methods to operate on either the outer array or the inner arrays. To operate on an inner array, you fetch that element from the outer array and then just treat it as an array. For example:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
var innerArray = dataArray[0];
console.log(innerArray); // [1,2,3]
innerArray.push(12);
console.log(innerArray); // [1,2,3,12]
innerArray.legnth = 2;
console.log(innerArray); // [1,2]
innerArray.push(9,8,7);
console.log(innerArray); // [1,2,9,8,7]
innerArray.splice(1,2);
console.log(innerArray); // [1,8,7]
You have wrote "I am trying to add array of arrays dynamically in javascript"
The simple way is using Array.prototype.push method:
var arr1 = [1,2], arr2 = [3,4], arr3 = [5,6], arr4 = [7,8], arr5 = [9,10],
dataArray = [];
[].push.apply(dataArray, [arr1, arr2, arr3, arr4, arr5]);
console.log(JSON.stringify(dataArray, 0, 4));
The console.log output:
[
[
1,
2
],
[
3,
4
],
[
5,
6
],
[
7,
8
],
[
9,
10
]
]
There are tons of way you can do this. A simple one could be
var arrayN = n => Array(n).fill([])
document.write("<pre>" + JSON.stringify(arrayN(10)) + "</pre>")
On another thinking if you already have arrays of arrays then the most simplified way of concatenating them in place should be using the new spread operator like;
var arr = [[1,2,3],[1,3,5]],
brr = [[3,2,1],[7,8,9]];
arr.push(...brr);
document.write("<pre>" + JSON.stringify(arr) + "</pre>");

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