Filth Filth - 2 months ago 7
Javascript Question

Duplicate numbers in array | Javascript

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/

Answer

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

Comments