-1

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.

Eddie
  • 26,593
  • 6
  • 36
  • 58
Gaurav Jadhav
  • 75
  • 1
  • 6

2 Answers2

1

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}`))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

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);
solanki...
  • 4,982
  • 2
  • 27
  • 29