-1

Let's say I have an arbitrary number of arrays that are the same length. I want to merge them together into another array.

What I mean by merge is to combine each value of the arrays together into the output array.

Can I get a function merge(...arrays) that can do this?

Type Definition (might be wrong): <T extends Array<U>, U>(...arr: T[]) => [...T][]

merge([A, B], [C, D])[[A, C], [B, D]]

Examples:

  • merge([1, 2, 3], [10, 20, 30])[[1, 10], [2, 20], [3, 30]]
  • merge([1, 2, 3])[[1], [2], [3]]
  • merge([1, "", {}], [17, { a: 1 }, "a"])[[1, 17], ["", { a: 1 }], [{}, "a"]]
  • merge([])[]

EDIT: Also, please provide a TypeScript Type definition for the function.

Shivam
  • 1,345
  • 7
  • 28

2 Answers2

1

You can't determine the type of an array element with TypeScript. If the array elements are of a known type, you could use the type argument in the function to help you getting the type when returning the result. But TypeScript would never be able to determine if an element of an array is an object with certain properties.

@iota suggestion is great. Array.map() is the best. I have only added a check that throws an error if the arrays are not the same size.


function merge<U>(...arrs: Array<Array<U>>): U[][] {
    const { length: firstLength } = arrs[0];
    if (!arrs.every((arr) => arr.length == firstLength)) {
        throw new Error('Arrays are not the same size.');
    }
    return arrs[0].map((_, i)=>arrs.map(x => x[i]));
}
// arrays are arbritrary in type
// inform `any` as type parameter
const a = merge<any>([1, "", {}], [17, { a: 1 }, "a"]);
// a is any[][]

// arrays are made of numbers
// tell typescript that 
const b = merge<number>([1, 2, 3], [10, 20, 30]))
// b is number[][]

// try hacking that...
const c = merge<number>([1, "", {}], [17, { a: 1 }, "a"]))
// ts error Type 'string' is not assignable to type 'number'.
//          Type '{}' is not assignable to type 'number'.
Bruno Polo
  • 657
  • 5
  • 11
0

You can use Array#map.

function merge(...arrs){
  return arrs[0].map((_, i)=>arrs.map(x => x[i]));
}
console.log(JSON.stringify(merge([1, 2, 3], [10, 20, 30])));
console.log(JSON.stringify(merge([1, 2, 3])));
console.log(JSON.stringify(merge([1, "", {}], [17, { a: 1 }, "a"])));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80