Ask Your Question
0

What is a concise method to insert an element between every element in a JavaScript array?

asked 2022-02-22 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-10-18 22:00:00 +0000

david gravatar image

One possible concise method to insert an element between every element in a JavaScript array is to use the flatMap() method to return a new array with the original values and the desired element concatenated between them. For example:

const originalArray = [1, 2, 3];
const insertElement = 0;
const newArray = originalArray.flatMap(value => [value, insertElement]);
// newArray is [1, 0, 2, 0, 3]

The flatMap() method applies a function to each element of the original array, returning a new array that flattens the resulting arrays into a single one. In this case, the function returns an array with the original value and the insert element, which is then flattened into the final array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-22 11:00:00 +0000

Seen: 7 times

Last updated: Oct 18 '21