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 :
['OVO','Dana','Shopepay','Gopay']
how to achieve that in javascript? thanks in advance.
CodePudding user response:
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);
CodePudding user response:
Use .reduce() to achieve your goal
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}
];
const max = arrays.reduce((prev, current) => (prev.length > Object.keys(current).length) ? prev : Object.keys(current)).splice(1)
console.log(max)