Reputation: 66
The ultimate goal is to be able to iterate through multiple arrays as if they are one. A strange challenge that comes with this is that when changes are made to any of the multiple arrays, the iteration process needs to seamlessly update. One way around this would be to simply combine the original lists and set them equal to a new variable, then set it equal again to the combination of the original lists every time a change is made, but if this is the best solution I would rather avoid this concept entirely.
My first approach was to try to make use of referencing. When an array is set to be equal to another array, any changes to the initial array, or, array_1 will result in a change to the latter array, array_2. That is because array_2 references array_1.
var list_1 = [1, 2];
var list_2 = list_1;
list_1.push(3)
console.log(list_1 === list_2);
console.log(list_2);
This does not, however, continue to be true in the various ways I've tried to set multiple arrays equal to a single array.
var list_1 = [1, 2];
var list_2 = [3, 4];
var list_3 = list_1.concat(list_2);
list_2.push(5)
console.log(list_2 === list_3);
console.log(list_3);
I've tried every method of combining multiple arrays I could find and none of them work how I want them to. Any changes to the original arrays does not result in a change to the output array.
My second approach was to try to combine the two lists somehow in the iterator, like (list_1, list_2).forEach((item) => {}
which didn't work and as I am new to javascript, was as far as I could get with the idea.
Here's a mockup of code that doesn't run, with an outcome I would like to see.
var list_1 = [1, 2];
var list_2 = [3, 4];
var list_3 = list_1.concat(list_2);
list_2.push(5)
list_3.forEach((item) => {console.log(item)});
// or even (list_1, list_2).forEach((item) => {console.log(item)});
/* desired output:
1
2
3
4
5
*/
/* real output:
1
2
3
4
*/
Upvotes: 0
Views: 1120
Reputation: 1
You could manually assign the multiple arrays to the output array.
const a=[1,2]
const b=[3,4]
let x=[a,b]
Then use Array.flat or your own implementation for flattening the output array,like this
b.push(5)
x.flat()// 1,2,3,4,5
Upvotes: 0
Reputation: 3770
You can use generators like this:
function* all(...arrays) {
for(let arrayIndex = 0; arrayIndex < arrays.length; arrayIndex++) {
for(let indexInArray = 0; indexInArray < arrays[arrayIndex].length; indexInArray++) {
yield arrays[arrayIndex][indexInArray];
}
}
}
const a1 = [1, 2];
const a2 = [3, 4];
const mergedForOfExample = all(a1, a2);
const mergedForEachExample = all(a1, a2);
a2.push(5)
for(let item of mergedForOfExample) {
console.log(item);
}
// or to get it as an array
const merged = Array.from(mergedForEachExample);
merged.forEach(item => console.log(item));
The disadvantage here is that once you finish iterate over all items you can’t iterate again (when not using the Array.from
)
Upvotes: 1