'How can I can create an array that merges the first 2 lists from another array?
Let's say that I have the following array:
[[1],[2],[3],[4],[5]]
How can I create a new array that looks like this:
[[1,2],[2,3],[3,4],[4,5]]
In my case I need to "merge" the data from 50 arrays, and then the next 50 arrays, and so on.
Solution 1:[1]
Try this:
arr = [[1],[2],[3],[4],[5]]
merged = [[arr[i][0], arr[i+1][0]] for i in range(len(arr)-1)]
gives
[[1, 2], [2, 3], [3, 4], [4, 5]]
Solution 2:[2]
function createAdjacentPair(arr){
let collection = [];
function helper(arr, memo={}){
if(arr.length === 1){
return null
}
const pair = arr[0].concat(arr[1])
const key = pair.join()
if(memo[key]) {
return memo[key];
}
collection.push(pair)
memo[key] = helper(arr.slice(1), memo)
return memo[key]
}
helper(arr)
return collection;
}
console.log(createAdjacentPair([[1],[2],[3],[4],[5]]))
I think this will do!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jan Wilamowski |
| Solution 2 | Sanjeev Shakya |
