2

So I'm trying to duplicate the array elements, for example:

var array = ["chicken","nugget","good"];

into:

var array2 = ["chicken","chicken","nugget","nugget","good","good"];

How to done with this?

Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
Awotism
  • 58
  • 6

3 Answers3

5

The idiomatic way would be:

["chicken","nugget","good"].flatMap((x) => [x, x]);

Be aware not all javascript environments have flatMap available yet so transpilation may be required.

david
  • 17,925
  • 4
  • 43
  • 57
2

You could try this:

const arr = ["chicken","nugget","good"].reduce(function (res, current, index, array) {
        return res.concat([current, current]);
    }, []);
iliya.rudberg
  • 739
  • 12
  • 23
2

One approach is to use forEach() to iterate over the array and insert each item twice into a new array.

var array = ["chicken","nugget","good"];

let array2 = [];

array.forEach(item => {
  array2.push(item, item);
});

console.log(array2);

NOTE: If array items are objects, by this method you are duplicating the same reference. In such case, you might want to clone the object before inserting.

Nikhil
  • 6,493
  • 10
  • 31
  • 68