How to duplicate elements of an array in Node.js?

Viewed 1117

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?

3 Answers

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.

You could try this:

const arr = ["chicken","nugget","good"].reduce(function (res, current, index, array) {
        return res.concat([current, current]);
    }, []);

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.

Related