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

Divide array to group indexes

I have a problem with the following logic in Javascript.

I have the following array, that have dynamic number of indexes, in this example I write one array with 2 indexes.

[[S,Blue],[M,Red],[L,Yellow]

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

I want to have this structure:
{ 0: [S,M,L], 1: [Blue,Red,Yellow] }

The numbers are the indexes of first group of array, what can I do?

I tried with for and map function but I don’t have the correct Logic

>Solution :

You can do this easily by first creating an object with Object.fromEntries(), then using Object.keys() and Object.values() to create an array.

function convertData(data) {
  const obj = Object.fromEntries(data);
  return [Object.keys(obj), Object.values(obj)];
}

const data = [['S', 'Blue'], ['M', 'Red'], ['L', 'Yellow']]
console.log(convertData(data))

Note: an object with numerical keys is the same as an array, therefore, you only need to create an array to fulfill the requirement.

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