I have two arrays which will always have the same number of elements within them.
var array1 = [["John","Barry","Anne"],["Greg"],["Tom"],["Roy","Rye"]]
var array2 = ["Banana","Orange","Apple","Grape","Pineapple","Raspberry","Pear"]
I want array2 to have the same array structure as array1, so it should look like:
var newArray = [["Banana","Orange","Apple"],["Grape"],["Pineapple"],["Raspberry","Pear"]]
I have tried using the length of array1 to firstly create a new array of the right length and then looping over that array to create the nested arrays with the right length. Then using a for loop, pushing array2's element to this new array but I'm having trouble figuring out how to do it.
var array = new Array(array1.length)
var arrayLength = array1.map(x => x.length)
for (var i = 0; i < array.length; i++) {
array[i] = new Array(arrayLength[i]);
}
for (var k = 0; k < array.length; k++) {
for (var j = 0; j < array[k].length; j++) {
array[0][k].push(array2[j])
}
}
Thanks for any help!
You can use .map() and .splice() to get the expected result.
If array2 is not allowed to be changed, we need a copy of it -> .slice()
const array1 = [["John", "Barry", "Anne"], ["Greg"], ["Tom"], ["Roy", "Rye"]];
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry","Pear"];
// if array2 can be modified, then this is not necessary
// and you have to replace <clone> with <array2> in the block below
const clone = array2.slice();
const newArray = array1.map(inner => {
return clone.splice(0, inner.length);
});
console.log(newArray);
Answer for the first version of the question
You only need .map() (twice) and a little bit of math for this.
const array1 = [
[1, 2, 3],
[4],
[5],
[6, 7]
];
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry", "Pear"];
const newArray = array1.map(inner => {
return inner.map(n => {
return array2[n - 1];
})
});
console.log(newArray);
(can be written as a one-liner but for easier readability I've used an explicit return)
const array1 = [["John", "Barry", "Anne"], ["Greg"], ["Tom"], ["Roy", "Rye"]];
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry","Pear"];
let indexTracker=0;
const newArr = array1.map(nameArr => nameArr.map(_ => array2[indexTracker++]));
console.log(newArr);
Use Array.map() and Array.slice() to get the final result.
const array1 = [[1, 2, 3], [4], [5], [6, 7]]
const array2 = ["Banana", "Orange", "Apple", "Grape", "Pineapple", "Raspberry", "Pear"]
let index = 0;
const finalArray = array1.map((itemList) => {
const list = array2.slice(index, index + itemList.length);
index += itemList.length;
return list;
});
console.log(finalArray);