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/

5
  • 4
    var result = numbers.concat(numbers); Commented Sep 13, 2016 at 15:21
  • How did you think would map work? Commented Sep 13, 2016 at 15:24
  • Iterate through each number and return them again at the end of the array Commented Sep 13, 2016 at 15:24
  • map is (more or less) for (i = 0; i < a.length; i++) r[i] = f(a[i]); What you describe would be for (i = 0, l = a.length; i < l; i++) a.push(f(a[i]));, which is not what map does. Commented Sep 13, 2016 at 15:26
  • Duplicate question [stackoverflow.com/questions/1960473/unique-values-in-an-array] Commented Sep 13, 2016 at 15:28

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

It's even faster if you omit the slice
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.