There are different ways to merge two arrays in JavaScript. You can use one of the following:
using the spread operator e.g.
[ ...array1, ...array2]using Array.prototype.concat()
using Array.prototype.push()
None of those will help if you need to merge two arrays to a Map or key/value pair for specific use. Given the example form below, we want to convert the separate array of keys and values, into an object.
How do we merge the form data to give us an object like what you see below?
{
"DB_URL": "example.com",
"NODE_ENV": "production"
}
Solution
We're going to create a function that takes in two arguments: one for the array of keys, and the other for the values. That function will use the reduce() method to produce an object of key/value pair.
This is how the function will look like:
function mergeArraysToMap(keys: string[], values: string[]): { [key: string]: string } {
if (keys.length !== values.length) {
throw new Error("The number of keys and values must be the same.");
}
// Use reduce to create the key/value map
const mergedMap: { [key: string]: string } = keys.reduce((map, key, index) => {
map[key] = values[index];
return map;
}, {});
return mergedMap;
}
The mergeArraysToMap function takes two arrays (keys and values) as arguments. It checks if the number of keys and values is the same and then uses the reduce method to create the key/value map. Then it returns the merged key/value pair.
We can take this further and ensure that we don't accept an empty string for the key or value. For that, we can modify the reduce method as follows:
const mergedMap: { [key: string]: string } = keys.reduce(
(map, key, index) => {
if ((key && !values[index]) || (!key && values[index]))
throw new Error("invalid key/pair");
if (key && values[index]) map[key] = values[index];
return map;
},
{} as Record<string, string>
);
With that implementation, we can be sure that we will get a valid key/value pair.
You can play around with the code on the TypeScript playground using this link.

Top comments (4)
Good use of reduce but the conditions you add could be improved:
Thanks for the contribution. Using
!key || !valuewill cause an error when both key and value are empty. In this case, I'd want them to be treated as null/undefined. That is, don't throw an error but don't add them to the Map.For numeric properties, it can be adapted to cover that specific usecase.
hola ka daar mfewethu...
I would like to know would it be not really wrong but ...what if I dont use these map() and reduce() methods to get things done but I use for(){} iterator?
What do you think of that? would it be less pro or unlean even unclean or otherwise what?
Would you be able to make an example of the above utilizing an iterator like for().
Any array iteration method can of course be replicated with a standard for() loop. If you're still learning then it's a useful exercise in order to understand what array methods do internally...
In terms of professional use; the array methods are now so standard that you would normally be expected to use them; since it helps with code readability. Seeing map(), reduce(), filter() gives a clear indication of what the loop is doing; whereas with a for() loop you have to look into the loop implementation to figure it out.
There used to be an exception where performance was concerned; but I must admit I don't know if it's still the case that a for() loop would - for example - outperform a reduce().