Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  131] [ 1]  / answers: 1 / hits: 16037  / 9 Years ago, mon, july 27, 2015, 12:00:00

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

More From » arrays

 Answers
3

What's wrong with your current code, is that your doubled function is returning nothing (which means it's returning undefined).



A better function would look like this:



function doubled (arr) {
var doubled = [];
for (var i = 0; i < arr.length; i++) {
doubled.push(arr[i] * 2);
}
return doubled;
}


However, an even better solution would be to just do this:



var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function (n) { return n * 2; })
};


.map is awesome.


[#65665] Friday, July 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aden

Total Points: 369
Total Questions: 100
Total Answers: 83

Location: Australia
Member since Tue, Oct 19, 2021
3 Years ago
;