Home > Mobile >  How can I can create an array that merges the first 2 lists from another array?
How can I can create an array that merges the first 2 lists from another array?

Time:03-10

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.

CodePudding user response:

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]]

CodePudding user response:

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!

  • Related