How can two arrays be effectively combined by their individual values?

Suppose I have an unspecified number of arrays all with the same length. My goal is to merge them into a single array.

When I say merge, I mean combining the values from each array into the output array.

Is there a function called merge(...arrays) that can achieve this?

Type Definition (potentially incorrect):

<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([])[]

UPDATE: Additionally, please provide a TypeScript Type definition for the function.

Answer №1

When working with TypeScript, it's not possible to directly determine the type of an element within an array. However, if you are dealing with arrays containing elements of a known type, you can utilize the type argument in your functions to assist in determining the type when returning results. Keep in mind that TypeScript cannot automatically infer whether an element within an array is an object with specific properties.

An excellent suggestion by @iota is to use Array.map() for this purpose. To enhance this approach, I've included a conditional check to throw an error if the arrays being compared do not have the same length.


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]));
}
// Example usage: Arrays can be of any type
const a = merge<any>([1, "", {}], [17, { a: 1 }, "a"]);
// Output: a is any[][]

// Example usage: Arrays are comprised of numbers
const b = merge<number>([1, 2, 3], [10, 20, 30]);
// Output: b is number[][]

// Attempting to mix different types will result in a TypeScript error
const c = merge<number>([1, "", {}], [17, { a: 1 }, "a"]);
// Output: Type 'string' is not assignable to type 'number'.
//         Type '{}' is not assignable to type 'number'.

Answer №2

To achieve this, utilize the Array#map method.

function combineArrays(...arrays){
  return arrays[0].map((_, index)=>arrays.map(array => array[index]));
}
console.log(JSON.stringify(combineArrays([1, 2, 3], [10, 20, 30])));
console.log(JSON.stringify(combineArrays([1, 2, 3])));
console.log(JSON.stringify(combineArrays([1, "", {}], [17, { a: 1 }, "a"])));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NodeJS introduces the nullish coalescing assignment operator (??=) for effective nullish value handling

Is it possible to use the Nullish coalescing assignment operator (??=) in NodeJS? const setValue = (object, path, value) => { const indices = { first: 0, second: 1 }, keys = path.replace(new RegExp(Object.keys(indices).join('| ...

Is it possible to use the Stop Button on the HTML5 Audio Tag to halt a live MP3 stream

Is there a way to add a stop button as well? Currently, I have play and pause buttons, but the stop function doesn't truly clear the music buffer in the browser; it just stops playback without resetting to the beginning. This is fine for MP3 files but ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

Memory allocation for a string array parameter passed by reference

How should memory be correctly allocated and freed in this scenario? void test(char*** array, int* count) { *array = malloc(sizeof(char*) * MAX_ARRAY); while (...) { (*array)[i] = (char*)malloc(strlen(fooString)); } } Function call example: c ...

Are there any @types available for browser extension objects that are interoperable?

I am in the process of developing a browser extension that would work seamlessly on Edge, Chrome, and Firefox by utilizing Typescript. After coming across an article discussing interoperable browser extensions, I stumbled upon a code snippet: window.brow ...

What is the best way to retrieve and display a detailed JSON object within views using Node.js?

Below is a snippet of code that deals with JSON arrays and how to handle them in a server setting. When sending data from the server, the code constructs a URL based on certain parameters and makes a request. If successful, it then logs the response and e ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Exploring React's Capabilities with DOM Manipulation Libraries

When working with React and the OpenSheetMusikDisplay library, I have a situation where I dynamically add elements below a target in the DOM. The target element is a div that I reference using a ref, and everything works smoothly. However, I also need to a ...

I can't figure out why my async delete function for a REST API in a ReactJS app is failing to execute correctly

Why isn't my onclick() remove method working in this react component? I've verified that the DELETE api call functions correctly using Postman and all the information is displayed correctly on the interface. However, when I click the delete butto ...

Using JSON / jQuery: How to Handle XML Data in the Success Function of an AJAX Post Request

Greetings! I am currently performing an ajax post through a JSP. The JSON data is being sent in string format (parsed using parseJSON, then converted back to a string using JSON stringify). The post operation functions correctly. However, my query lies in ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Troubleshooting Wordpress Custom Widget with Missing Javascript Output

I've encountered an issue with my JavaScript code that I wrote for a custom widget. Below is the code snippet from my JavaScript file and how I'm implementing it in the widget: Custom.js var container = $('#container'); ...

Transform a list separated by commas into an unordered list

Seeking a PHP, Jquery, or JavaScript method to convert comma-separated data into an unordered list. For clarification, I have uploaded a CSV file to WordPress where one section of content is separated by commas and I am looking to display it as a list. A ...

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

What is the best way to utilize state and an object's keys in React to dynamically style components?

I am working with Create React App (CRA) and Axios, and I'm facing a specific challenge. I want to create a basic stock chart that showcases exchange rates. The component should load on mount, make a call to a static API using Axios, and populate the ...

Style will be applied to Angular2 when the object's ID exceeds 100

I am working with object markers that have different Id's assigned to them. Now, I am trying to apply additional styling when the id > 100. Check out the code snippet below: <span *ngIf="result.object.reference > 100" class="tooltip-data"&g ...

Utilize JavaScript or jQuery to align a list item center on a horizontal scrolling navigation bar

Currently, I am utilizing bootstrap 4.6 for a webpage, and while the default navbar doesn't meet my requirements for mobile navigation, I am attempting to customize it to function like MODE_SCROLLABLE in Android. Therefore, I need it to activate the l ...

Is it possible to incorporate numerous instances of SlickGrid by utilizing an angular directive?

Just started diving into AngularJS and it's been an exciting journey so far. I've come across the suggestion of wrapping external libraries into directories, which definitely seems like a good practice. While trying to create a 'slickgrid& ...

the proper injection of angular-resource is not being achieved in AMD

I am struggling to get angular.resource.js to work with angular.js. It seems like Angular is loaded but angular.resource is not being recognized. index.html <!doctype html> <html> <head> <script> var require ...