0

For the life of me I can't figure out how to duplicate the numbers array.

Expected result: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Here is my code so far:

const numbers = [1, 2, 3, 4, 5];
var result = numbers.map((number) => {
    return number
});

console.log(result);

I can't figure out how you can take the numbers array and then duplicate the array?

I was starting to do if statements - "If number is equal to 1 then return 1" but that would print the numbers like this [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

https://jsfiddle.net/e6jf74n7/1/

Filth
  • 3,116
  • 14
  • 51
  • 79

3 Answers3

3

Map will map all values one-to-one, that's why it's called "map"; it gives you one value, you return a value that should replace it.

To duplicate a list, concat the list to itself:

const numbers = [1, 2, 3, 4, 5];
var result = numbers.concat(numbers);

console.log(result);
deceze
  • 510,633
  • 85
  • 743
  • 889
0

Map won't work in this case just use concat

numbers.concat(numbers);

If you want to concat multiple times then

var concatArr = numbers;
 for (var i=0; i < 9 ; i++ ) {  
        numbers = numbers.concat(concatArr); 
   }
  console.log(numbers);

Concat docs https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

KrishCdbry
  • 1,049
  • 11
  • 19
0

fastest way is to use slice() then concat() to old array.

var arr = [ 1, 2, 3, 4, 5 ];
var clone = arr.slice(0);
var duplicate = arr.concat(clone);