Using .map() on an array full of undefined values (eg new Array(10)) will always return an array of the same length with undefined values, no matter what you return.
new Array(10).map(function(){return 5;});
will return a new array filled with 10x undefined. Why does this happen?
Because when you define an array like that, the spaces for values are empty slots and are not iterated over by map() or any of its friends.
There is Array.prototype.fill() (in ES6) which can be used to set values on that array.
You could use
var array = Array.apply(null, { length: 10 }).map(function(){ return 5; });
var array = Array.apply(null, { length: 10 }).map(function() { return 5; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
from the fine manual:
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).
new Array(10)
creates missing elements, if that makes any sense.
Like this one:
var b=new Array();
b[30] = 1;
var c = b.map(function(){return 5;});
> [undefined × 30, 5]
There's an answer for this here: https://stackoverflow.com/a/5501711/6206601. Look at the top comment for further clarification.
Related
I am studying now at FreeCodeCamp, and here is a challenge:
"We have defined a function, copyMachine which takes arr (an array)
and num (a number) as arguments. The function is supposed to return a
new array made up of num copies of arr. We have done most of the work
for you, but it doesn't work quite right yet. Modify the function
using spread syntax so that it works correctly (hint: another method
we have already covered might come in handy here!)."
And here is a solution:
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// Only change code below this line
newArr.push([...arr])
// Only change code above this line
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
What the point to add extra brackets and dots (...) if i could just add newArr.push(arr) instead and get the same result?
The result is: [ [ true, false, true ], [ true, false, true ] ]
It's the matter of reference.
When using this syntax newArr.push(arr), you're pushing the original array from the argument, so whenever the arr changes its content, arrays inside newArr will also update since it is always the same one array.
When using spread syntax, you're actually pushing a copy of that arr. This mean it's a new array that is not tied to the array you pass to a function
Consider this
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// Only change code below this line
newArr.push(arr)
// Only change code above this line
num--;
}
return newArr;
}
const oldArr = [true, false, true];
const newArr = copyMachine(oldArr, 2);
oldArr.push(true);
console.log(newArr); // contains an element added to the old array
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
In the provided code the spread operator is used to make a new array using the elements of the array named arr and then push it onto newArr.
This is similar to doing newArr.push(arr);
Hoping someone can shed some light on this simple piece of code not working as expected:
var arr = new Array(10);
arr.length; // 10. Why? Very wierd.
Why does it return 10?
You instantiated the array with ten elements
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If the only argument passed to the Array constructor is an integer
between 0 and 232-1 (inclusive), this returns a new JavaScript array
with its length property set to that number
So it is impossible to create a new array with only one number element using the new keyword.
You can however do :
var arr = [10]; // Creates a new array with one element (the number 10)
console.log(arr.length); // displays 1 because the array contains one element.
I makes an Array with 10 cells... so it returns 10 :)
You wanted to do:
var arr = [10]
It returns 10, because you give only one integer, as argument, to the Array constructor. In this case, the new Array constructor is acting like some programming languages where you needed to specify the memory for your array so you don't get those ArrayIndexOutOfBounds Exceptions.
An example of this in Java:
int[] a = new int[10];
Or C#:
int[] array = new int[5];
In Javascript, when you write:
var a = new Array(10);
a[0] // returns undefined
a.length // returns 10.
and if you write:
a.toString() // returns ",,,,,,,,,", a comma for each element + 1
But, since Javascript doesn't need to allocate memory for an array, is better to use use the [] constructor:
var a = [10];
a[0] //returns 10
a.length //returns 1
I think that the thing that confuse all the people is this:
var a = new Array(1,2,3,4,5);
a[0] // returns 1
a.length // returns 5
But you can do the same in this way:
var a = [1,2,3,4,5];
a[0] // returns 1
a.length // returns 5
So, in conclusion, try to avoid using the new Array constructor, and use the [] constructor instead.
it's my first question here, after have been reading for years, so be nice with me please.
I'm having trouble with array management in js/jq.
I have array with several elements, which is processed with $.each function.
I want to extract matching elements to another array and return this array.
But for some reason (don't know if it's because array declaration, jquery.each function...) I'm having first empty element.
I think I'm making this more difficult to understand than it's, so made jsfiddle.
var arr = new Array();
$.each([1,2,3], function(index,element){
if (element == 2){
arr[index] = element;
}
});
arr must have only 1 element, but arr.length returns 2 because first array slot is empty.
Here is a fiddle http://jsfiddle.net/moay7y95/
I'm so sure that it's a simple and little stupid thing, but I've not been able to find an answer.
Thanks in advance!
You are pushing an element in array at 1st index. So, javascript by default put undefined at 0th index.
So, at the end of each your array will be
[undefined, 2];
This is the reason you get the length as 2.
You can use push to add element in array:
$.each([1, 2, 3], function (index, element) {
if (element == 2) {
arr.push(element);
elem++;
}
});
Demo: https://jsfiddle.net/tusharj/moay7y95/2/
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Docs: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Best solution: Use .filter
var arr = [1, 2, 3].filter(function(value){
return value == 2
});
If the return value is true, the element is included in the returned array, otherwise it is ignored. This is pure js, so you don't need jquery. See documentation about .filter
Your problem: Use .push
Try using the .push method on the array (see Mozilla's documentation).
var arr = new Array();
$.each([1,2,3], function(index,element){
if (element == 2){
arr.push(element);
}
});
The .push method will dynamically grow your array as elements are added.
Your problem is that the value of index inside your function is a reference point in your initial array. This means that if you look at the returned array, you will find [undefined, 2] and so the length is returning as 2. If your condition were element == 3 you would have two empty slots.
Alternatively: Use .grep
Another jQuery method is $.grep. See http://api.jquery.com/jquery.grep/
var arr = $.grep([1, 2, 3], function (value) {
return value == 2
});
This is jQuery's implementation of javascript's .filter.
Your array [1, 2, 3] has three elements, and three associated indexes: 0, 1 and 2. In each iteration of your $.each() loop over that array, the index and its value get passed to the function.
So the first call gets 0, 1 passed as its arguments. The second call gets 1, 2 passed as its arguments, then the if statement condition evaluates to true, so your code:
arr[index] = element;
is actually equivalent to
arr[1] = 2;
Since you're inserting an element at index 1, you'll end up with an empty index 0.
You could instead simply use Array.push() to add the element to the array:
arr.push(element);
As already mentioned the problem is you are assigning the value at index 1, so the array will be considered of length 2.
One solution is to use .push() instead of assigning based on index.
Another approach could be is to use Array.filter() and return true if the element matches the conditon
var arr = [1, 2, 3].filter(function(value){
return value == 2
});
Demo: Fiddle
Using $.grep()
var arr = $.grep([1, 2, 3], function (value) {
return value == 2
});
[1, 2, 3]
if (element == 2)
arr[index] = element;
This means you're setting arr[1] to element.
If you want to add it to the arr sequentially (filling it up normally), push it into art
arr.push(element);
Seems like you're looking for Array.filter (MDN).
var elems = ["car", "bike"];
var arr = [1, 2, 3, "car", 5, "bike"].filter(myFilterFunc);
function myFilterFunc(val) {
if (elems.indexOf(val) > -1) return true;
}
Fiddle
This question already has answers here:
Undefined values in Array(len) initializer
(5 answers)
Closed 7 years ago.
I am confused by the results of mapping over an array created with new:
function returnsFourteen() {
return 14;
}
var a = new Array(4);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
a.map(returnsFourteen);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
var b = [undefined, undefined, undefined, undefined];
> [undefined, undefined, undefined, undefined]
b.map(returnsFourteen);
> [14, 14, 14, 14]
I expected a.map(returnsFourteen) to return [14, 14, 14, 14] (the same as b.map(returnsFourteen), because according to the MDN page on arrays:
If the only argument passed to the Array constructor is an integer
between 0 and 2**32-1 (inclusive), a new JavaScript array is created
with that number of elements.
I interpret that to mean that a should have 4 elements.
What am I missing here?
When you create an array like so:
var arr1 = new Array( 4 );
you get an array that has a length of 4, but that has no elements. That's why map doesn't tranform the array - the array has no elements to be transformed.
On the other hand, if you do:
var arr2 = [ undefined, undefined, undefined, undefined ];
you get and array that also has a length of 4, but that does have 4 elements.
Notice the difference between having no elements, and having elements which values are undefined. Unfortunately, the property accessor expression will evaluate to the undefined value in both cases, so:
arr1[0] // undefined
arr2[0] // undefined
However, there is a way to differentiate these two arrays:
'0' in arr1 // false
'0' in arr2 // true
var a = new Array(4);
This defines a new array object with an explicit length of 4, but no elements.
var b = [undefined, undefined, undefined, undefined];
This defines a new array object with an implicit length of 4, with 4 elements, each with the value undefined.
From the docs:
callback is invoked only for indexes of the array which have assigned
values; it is not invoked for indexes which have been deleted or which
have never been assigned values.
For array a, there are no elements that have been assigned values, so it does nothing.
For array b, there are four elements that have been assigned values (yes, undefined is a value), so it maps all four elements to the number 14.
new Array(len) creates an empty array, and does something different than filling it with undefined values: It sets its length to len. So, it translates to this code:
var newArr = [];
newArr.length = len;
Let's have some fun with newArr (assuming that len = 4):
newArr.length; //4
newArr[1] === undefined; //true
newArr.hasOwnProperty(1); //false
This is because while the is 4 items long, it does not contain any of these 4 items. Imagine an empty bullet-clip: It has space for, say, 20 bullets, but it doesn't contain any of them. They weren't even set to the value undefined, they just are...undefined (which is a bit confusing.)
Now, Array.prototype.map happily walks along your first array, chirping and whistling, and every time it sees an array item, it calls a function on it. But, as it walks along the empty bullet-clip, it sees no bullets. Sure, there are room for bullets, but that doesn't make them exist. In here, there is no value, because the key which maps to that value does not exist.
For the second array, which is filled with undefined values, the value is undefined, and so is the key. There is something inside b[1] or b[3], but that something isn't defined; but Array.prototype.map doesn't care, it'll operate on any value, as long as it has a key.
For further inspection in the spec:
new Array(len) : http://es5.github.com/#x15.4.2.2
Array.prototype.map : http://es5.github.com/#x15.4.4.19 (pay close attention to step 8.b)
One additional answer on the behavior of console.log. Plain simple, the output is sugar and technically wrong.
Lets consider this example:
var foo = new Array(4),
bar = [undefined, undefined, undefined, undefined];
console.log( Object.getOwnPropertyNames(bar) );
console.log( Object.getOwnPropertyNames(foo) );
As we can see in the result, the .getOwnPropertyNames function returns
["length"]
for the foo Array/Object, but
["length", "0", "1", "2", "3"]
for the bar Array/Object.
So, the console.log just fools you on outputting Arrays which just have a defined .length but no real property assignments.
I have some simple jQuery code:
var response = Array()
$('.task-list').each(function() {
response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);
The problem I'm having is that I think I'm using concat improperly- the result is an empty array. When I use array push, it works correctly.
You have to set response to the newly formed array, as described in the specification. You currently don't use the return value at all.
The specification says that for .concat, the array is not altered, but the new array is returned:
When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.
Compare with .push, which says the current array is altered, and that something else is returned instead (the new length):
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
So:
response = response.concat($('#' + this.id).sortable('toArray'));
Concat returns the concatenated array, you want this instead
response = response.concat($('#' + this.id).sortable('toArray'));
Simple example
var a = [1,2];
var b = [3,4];
a = a.concat( b ); // result is [1,2,3,4] which is correct
If you do the following
a = a.concat( a , b ); // result is [1, 2, 1, 2, 3, 4] not what you want.