Here is my first array:
const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
Here is my second array:
const arr = ['f', 'b', 'c', 'd'];
The number of arrays in withSub is always equal to the number of arr arrays, while the number of subarrays in withSub may be different.
I want to create a function that generates a new array based on these two arrays in such a way that the number of each element in arr must be equal to the number of subarrays in withArr.
In this example the final array must be:
['f', 'f', 'f', 'f', 'b', 'b', 'c', 'd', 'd'];
CodePudding user response:
If I understood your question correctly, you can use .flatMap()
on your withSub
array to map each number within each subarray to their corresponding letter from arr
. You can do this by taking the index of the subarray from the flatMap callback, and then use that to obtain the letter from arr
when mapping your subarrays.
See example below:
const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];
const res = withSub.flatMap((subArr, i) => subArr.map(() => arr[i]));
console.log(res);
CodePudding user response:
you can do something as the following code:
const generate = (numbers, letters) => {
return numbers.map((nums, i) => {
return nums.map(num => letters[i])
}).flat()
}
And then use it with generate(withSub, arr)
.
CodePudding user response:
You can have an approach with forEach()
and spread
operator.
forEach()
is similar to a forloop with subtle differences.
const awesomeFunction = (withSub , arr) => {
let ans = [];
arr.forEach( (x,index) => {
let newArr = new Array(withSub[index].length).fill(x);
ans = [...ans , ...newArr];
});
return ans; };
const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];
console.log(awesomeFunction(withSub,arr));
CodePudding user response:
Use a function with map and reduce
const processArr = (arr, withSub) => {
return arr.reduce((acc, el, index) => {
return [...acc, ...withSub[index].map(sub => el)];
}, []);
}
CodePudding user response:
You should try this.
const withSub = [[31, 32, 34, 34], [32, 36], [12], [15, 38]];
const arr = ['f', 'b', 'c', 'd'];
var res = [];
for(var i = 0; i < withSub.length; i ){
for(var j = 0; j < withSub[i].length; j ){
res.push(arr[i]);
}
}
console.log(res)