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

how to get index inside object on array to make it new obejct based on longest index

i have an array like this:

arrays = [
 {"y":"2020","OVO":3},
 {"y":"2021","OVO":2,"Dana":1},
 {"y":"2019","OVO":2,"Dana":1,"Shopepay":3},
 {"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1}, //length = 5
 {"y":"2022","OVO":2,"Dana":1,"Shopepay":1}
];

now i want to create new array based on longest object key from arrays.
should from this:

{"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1}, //length = 5

to this :

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

['OVO','Dana','Shopepay','Gopay']

how to achieve that in javascript?
thanks in advance.

>Solution :

Looking for something like this?

const arrays = [
 {"y":"2020","OVO":3},
 {"y":"2021","OVO":2,"Dana":1},
 {"y":"2019","OVO":2,"Dana":1,"Shopepay":3},
 {"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1},
 {"y":"2022","OVO":2,"Dana":1,"Shopepay":1}
];
const longestArray = arrays.sort((a, b) => Object.keys(a).length - Object.keys(b).length)?.pop(); // sort for most object with most properties

console.log(Object.keys(longestArray).slice(1)); // remove first element from array

Or as simple one-liner:

Object.keys(arrays.sort((a, b) => Object.keys(a).length - Object.keys(b).length)?.pop()).slice(1);
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