-1

I need to count the repeated characters in such an example, get an array and return an object. Example: Input: [ 'a', 'b', 'a', 'v'] Output: {a: 2, b: 1, v:1}, the cycles may not be used, as well as mutations or rigid array value assignment within reduce. Now my code looks like this, but it doesn’t work.

(arr) => {
  const arr2 = arr.filter((v, i, a) => a.indexOf(v) === i).map(v => [v, arr.filter(x => x === v).length
  ]) // [["a",2],["b",1],["v",1]]
  const obj = Object.fromEntries(arr2)
  return obj //undefined
}
georg
  • 211,518
  • 52
  • 313
  • 390
Orient87
  • 21
  • 2
  • 1
    where you are trying to execute your code? [Object.fromEntries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#Browser_compatibility) is not available everywhere yet – AZ_ Sep 27 '19 at 09:38

2 Answers2

0

You can get that output from a simple Array.forEach() logic without needing to use map(), filter() or any nested loops.

let arr = [ 'a', 'b', 'a', 'v'];
let resultObj = {};
arr.forEach((item) => {
  if(resultObj[item]) {
    resultObj[item]++;
  } else {
    resultObj[item] = 1;
  }
});
console.log(resultObj);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You don't need indexOf, just map and filter:

let arr = [...'abcxcbaa']

cnt = Object.fromEntries(
    arr.map(c =>
        [c, arr.filter(d => d === c).length]
    )
)

console.log(cnt)

Another idea is reduce + an accumulator object:

let arr = [...'abcxcbaa']

cnt = arr.reduce((r, c) => ({
    ...r,
    [c]: (r[c] || 0) + 1
}), {})

console.log(cnt)
georg
  • 211,518
  • 52
  • 313
  • 390