I have array,
$servArray = [AC Service,AC Installation,AC Service, AC Installation];
So I want to print,
AC Service = 2;
AC Installation = 2
How do I print both the values.
Thanks in advance.
I have array,
$servArray = [AC Service,AC Installation,AC Service, AC Installation];
So I want to print,
AC Service = 2;
AC Installation = 2
How do I print both the values.
Thanks in advance.
You can use reduce()
for that. Use an object as accumulator which will have array items as keys and values as their count. And then use forEach()
on Object.entrries
to iterate through them keys and values.
const $servArray = ['AC Service','AC Installation','AC Service', 'AC Installation'];
const getCount = (arr) => arr.reduce((ac,a) => {
ac[a] = ac[a] + 1 || 1;
return ac;
},{})
const res = getCount($servArray)
Object.entries(res).forEach(([key,value]) => console.log(`${key} = ${value}`))
We can use es6 map
function and iterate the array and assign the expected result in declared object.
const $servArray = ['AC Service','AC Installation','AC Service', 'AC Installation'];
const counts = {};
$servArray.map(x => counts[x] = (counts[x] || 0)+1);
console.log(counts);