-2

Assuming you have an array x = [1, 1, 2, 2, 2, 3], and you had to output a sorted array of objects containing a key-value pair (where the key represents the element, and the value the frequency) like:

y = [
        {
          2: 3
        },
        {
          1: 2
        },
        {
          3: 1
        }
    ]

The resulting array should be sorted by the values.

What would be the best way of doing this?

user2314737
  • 24,359
  • 17
  • 91
  • 104
mic
  • 3,851
  • 1
  • 18
  • 23
  • 3
    To get the best answers to your question we like to see a) that you've attempted to solve the problem yourself first, and b) used a [mcve] to narrow down the problem. As it stands this question is too broad. – Andy Nov 06 '18 at 13:17
  • 1
    `x.reduce((a, v) => { const ix = a.findIndex(i => Object.keys(i)[0] == v); if (ix < 0) a.push({[v]: 1}); else a[ix][v] += 1; return a; }, []).sort((a,b) => Object.keys(a)[0] - Object.keys(b)[0]);` – Keith Nov 06 '18 at 13:25
  • Similar question: [Counting the occurrences / frequency of array elements](https://stackoverflow.com/q/5667888/2314737) – user2314737 Aug 15 '20 at 07:53

1 Answers1

1

You can create a temporary object and do simple .forEach and check if current number exists in object as key, if true plus 1 to the value, otherwise create that key, then with simple .map add all key value pairs in separate object in new array

 const x = [1, 1, 2, 2, 2, 3];
 const k = {};
   x.forEach(v => {
     if(k[v]) {
        k[v] +=1;
     } else {
        k[v] = 1;
     }   
   });
const y = Object.keys(k).sort((t,c)  => k[c] - k[t]).map(key => ({[key]: k[key]}));
console.log(y);
Artyom Amiryan
  • 2,688
  • 1
  • 8
  • 20