Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join sequence of arrays with array delimeters ("intersperse")

Is there a function that lets me concat several arrays, with delimiters between them (the delimiters are also arrays), similarly to how join works but not restricted to strings?

The function can be standard JS or part of a major library such as lodash (which is why it's referenced in the tags).

Here is an example of usage:

let numbers = [[1], [2], [3]];
let result = _.joinArrays(numbers, [0]);
console.log(result); 
//printed: [1, 0, 2, 0, 3]

This is analogous to:

let strings = ["a", "b", "c"];
let result = strings.join(",");
console.log(result);
//printed: "a,b,c";

However, join can't be used because it turns values into strings, which I don't want to happen.

But it works for any type.

like image 581
GregRos Avatar asked Dec 14 '22 03:12

GregRos


1 Answers

You could simply use array.reduce to concat the arrays, and push what ever you want to use as your delimiter.

let numbers = [[1], [2], [3]];

let n = numbers.reduce((a, b) => a.concat(0, b))

console.log(n)
like image 148
DavidDomain Avatar answered Dec 16 '22 18:12

DavidDomain