-4

How can i convert this array

var array = ['a', 'b', 'c', 'd', 'a', 'b','c', 'd'] 

to an Object

object = { a:2 , b:2, c:2, d:2 }

using only javascript underscore _reduce ?

TkTn102
  • 1
  • 1

2 Answers2

1

arr.reduce((obj, currentKey) => {
  if(currentKey in obj) {
     obj[currentKey] = obk[currentKey] +1
  } else{ 
    obj[currentKey] = 1
  }

return obj;
}, {});

and testd on your code, here is the output

enter image description here

Ahmed Khattab
  • 2,645
  • 2
  • 13
  • 19
  • 1
    FYI - When you're posting an answer, the 7th button from the left (with an icon similar to `<>`) in the editor will allow you to create a working js snippet that will show the output of the code :) – Alon Eitan Feb 24 '20 at 10:03
  • 1
    thanks @AlonEitan , im kinda new so now very familiar to these stuff – Ahmed Khattab Feb 24 '20 at 10:27
0

I hope this will help

var array = ['a', 'b', 'c', 'd', 'a', 'b','c', 'd'];

var obj = [...new Set(array)]
    .reduce((acc, cur) => ({
      ...acc,
      [cur]: array.filter(item => item === cur).length
    }),
{});

console.log(obj);
Jay
  • 2,826
  • 2
  • 13
  • 28