0

Following one of the answers of How to count certain elements in array? created the JavaScript code below to build a Object, what can be used to build a Object named chars what can be used as chars.str and chars.num:

    const arr="abrakadabra".split('');
    const counts = {};
    arr.forEach((el) => {
      counts[el] = counts[el] ? (counts[el] += 1) : 1;
    });
    const countsSorted = Object.entries(counts).sort(([_, b], [__, a]) => a - b);
    console.log(countsSorted); // [["a",5],["b",2],["r",2],["k",1],["d",1]]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

What is the elegant way to create Object from countsSorted what can be used as chars.str and chars.num, like:

Object {
  num: [5, 2, 2, 1, 1],
  str: ["a", "b", "r", "k", "d"]
}
eapo
  • 1,053
  • 1
  • 19
  • 40

2 Answers2

0

With the help of JavaScript Array of Objects Tutorial I was able to understand more and have found the JavaScript Array forEach() Method as a solution. Working example below:

    const arr="abrakadabra".split('');
    const counts = {};
    arr.forEach((el) => {
      counts[el] = counts[el] ? (counts[el] += 1) : 1;
    });
    const countsSorted = Object.entries(counts).sort(([_, b], [__, a]) => a - b);

    var chars = new Object();
    chars.str = [];
    chars.num = [];
    
    countsSorted.forEach((asd) => {
      chars.str.push(asd[0]);
      chars.num.push(asd[1]);
    });

    console.log(chars); // {"str":["a","b","r","k","d"],"num":[5,2,2,1,1]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
eapo
  • 1,053
  • 1
  • 19
  • 40
0

You can use Array.reduce() to transform arrays to objects:

const str = "abrakadabra";

const countsSorted = Object.entries(
  str .split('').reduce((acc, el) => {
    acc[el] = (acc[el] ?? 0) + 1;

    return acc;
  }, {})
).sort(([, a], [, b]) => b - a);

const chars = countsSorted.reduce((acc, [str, num]) => {
  acc.str.push(str);
  acc.num.push(num);

  return acc;
}, { str: [], num: [] });

console.log(chars); // {"str":["a","b","r","k","d"],"num":[5,2,2,1,1]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209