Reputation: 396
Suppose I have an array :
const A = [1,2,3]
and I want to fill another array, say B
, with the elements of A
; B.length >> A.length
.
I am interested in any function that can help create array B
of the form:
[1,1,1,2,2,2,2,2,3,3,3,3,2,2,2,1,3,1]
The placements of the elements of A
into B
depends on specified index limits. Element 1 can be placed in several specified location/interval in B. The length of B
is known; N
is the length of B
.
In my trial, I tried to use the array.fill function, but don't know how to get the start and end indexes. Any help will be appreciated.
const A = [1,2,3];
const B = [];
for (let k = 0; k < A.length; k++){
for (let j = 0; j < N; j++){
B.fill(A[k], start_index[j], end_index[j]);
}
}
Upvotes: 0
Views: 882
Reputation: 396
To condense Barmar's suggestion:
const params = [
{index: [0,1,2,1,0,2,0], start: [0,3,8,12,15,16,17], end: [3,8,12,15,16,17,18]}
];
const A = [1, 2, 3];
const B = [];
for (let j=0; j<7;j++){
params.forEach(({index, start, end}) => {
if (B.length < end[j]) {
B.length = end[j];
}
B.fill(A[index[j]], start[j], end[j])
});
}
console.log(B);
Upvotes: 0
Reputation: 780818
Since you're filling multiple ranges of B
with the same element of A
, you need a data structure that has multiple start/end/index
combinations.
.fill()
won't extend the length of an array by itself, so you need to adjust the length when appending new elements.
const params = [
{index: 0, start: 0, end: 3},
{index: 1, start: 3, end: 8},
{index: 2, start: 8, end: 12},
{index: 1, start: 12, end: 15},
{index: 0, start: 15, end: 16},
{index: 2, start: 16, end: 17},
{index: 0, start: 17, end: 18}
];
const A = [1, 2, 3];
const B = [];
params.forEach(({index, start, end}) => {
if (B.length < end) {
B.length = end;
}
B.fill(A[index], start, end)
});
console.log(B);
Upvotes: 1