Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turning two arrays into an object : one array as keys and the other array as values

I have two arrays:
[ 'J', 'o', 'h', 'a', 'n']
[ 1, 1, 1, 2, 1]
I would like to use the first one as the object keys and the second one as object values. The result should be:
{ "J": 1, "o": 1, "h": 1, "a": 2, "n": 1}

Is this achievable with JavaScript ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Array.prototype.reduce to iterate over the arrays and create the object:

const keys = ["J", "o", "h", "a", "n"];
const values = [1, 1, 1, 2, 1];

// We are using reduce to iterate over the keys array and create an object
const result = keys.reduce(
  (
acc, // The first argument is the accumulator, which is the object we are building
key, // The second argument is the current value, which is the current key
i // The third argument is the index, which is the current index
  ) => {
// We are returning the accumulator with the current key and value
return {
  ...acc, // We are spreading the accumulator to keep the previous values
  [key]: values[i], // We are adding the current key and value
};
  },
  {} // The second argument for reduce is the initial value, which is an empty object this is used as the first value of the accumulator
);

console.log("result", result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading