This is a 2 step problem:
1.) I am trying to 'double' the contents of one array (original Array), save it in a new array (Doubled Array).
2.) Then assign those two arrays to an Object with 2 attributes. New Object Orginal Numbers Doubled Numbers
This is what I have so far, what am I doing wrong?
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
What's wrong with your current code, is that your
doubled
function is returning nothing (which means it's returningundefined
).A better function would look like this:
However, an even better solution would be to just do this:
.map
is awesome.using Array.from, you can double and return new array
To answer your original question, the reason you were seeing undefined in
collectionNumbers
is because you forgot to return doubledNumbers in your function (and functions by default returnundefined
.Your whole routine can be simplified to
using Array.map to create a new array with the doubled numbers
The best way to do this in Javascript is using the
map
function:The argument to
map
is the function that it uses to transform the elements in the first array into the elements in the second array. It is a tremendously useful method.