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.
Asked: 2022-02-22 11:00:00 +0000
Seen: 7 times
Last updated: Oct 18 '21