Reputation: 1083
If I have two immutable lists,
const a = [1,2,3];
const b = [a,b,c,d];
is there an easy way to merge/zip them to result in:
const c = [1,a,2,b,3,c,d];
Upvotes: 1
Views: 680
Reputation: 1152
If you want to develop a function from scratch then you can use the code below. Basically, the function merges the two array as interleaving the two. Consider 2 arrays, array1 = [1,2,3,4] and array2 = [a,b,c,d,e,f]. Then the below code will output a new array [1,a,2,b,3,c,4,d,e,f]
var i = 0;
var j = 0;
var k = 0;
var len1 = array1.length;
var len2 = array2.length;
var flag = true;
var newArr = [];
//Merge the 2 arrays till the smaller sized array
while (i < len1 && j < len2)
{
if(flag){
newArr[k] = array1[i];
i++; k++;
flag = false;
}
else{
newArr[k] = array2[j];
j++; k++;
flag = true;
}
}
/* Copy the remaining elements of array1[], if there are any */
while (i < len1)
{
newArr[k] = array1[i];
i++;
k++;
}
/* Copy the remaining elements of array2[], if there are any */
while (j < len2)
{
newArr[k] = array2[j];
j++;
k++;
}
console.log(newArr)
Upvotes: 0
Reputation: 7564
Is interleave what you are looking for: https://facebook.github.io/immutable-js/docs/#/List/interleave
const a = List([1, 2, 3]);
const b = List([a, b, c, d]);
a.interleave(b)
Upvotes: 1
Reputation: 59396
const a = [1, 2, 3]
don't make this array immutable at all. What const
does is to guarantee that you're not reassigning a
. Pushing or removing items to a
don't constitute a reassignment.
This is a real immutable list using immutable.js
:
const a = List([1, 2, 3]);
Now.. back to zip.
If you don't want another reference, you can just use a for
in the smallest list and build the zip yourself. If you want a ready-made function, you might consider using Underscore's Zip, which does exactly what you want.
Upvotes: 0