How to Convert Array to Object with ordering change?

I have a array now want to convert into object with ordering change.

My Code:-

arr = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0];

console.log({...arr});

but I want result like given below format, how can I achieve that?

OutPut: { function: 1, object: 4, number: 3, undefined: 1 }

Thanks for your efforts!

>Solution :

You just have to get the typeof each of the entries and sum it up in an object.

Here is an example:

const arr = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0];

const obj = arr.map(e => typeof e).reduce((o,t) => ({...o, [t]: (o[t] ?? 0) + 1 }), {})
console.log(obj);

Leave a Reply